Help with matrix and using fprintf with Matlab? I need help with my matlab code.
ID: 2074009 • Letter: H
Question
Help with matrix and using fprintf with Matlab?
I need help with my matlab code. I'm making a conversion table, and so far the code is able to do the conversion that I need, but only for 1 input at a time. However, I want to the user to be able to dictate the increments and the amount of lines that will compile in the output. This is where I get confused with the array/matrix thing. Here is what I have so far.
m=input('Please input the starting mile of the conversion table ');
i=input('Please input the increment between lines in miles (mi) ');
c=input('Now, please enter the number of lines to show in the conversion table ');
y=1760*m;
f=5280*m;
fprintf('Miles Yards Foot ');
fprintf('========================= ');
fprintf('%1.2f %1.1f %1.1f ',[m,y,f,]);
Explanation / Answer
first run this code with 'for loop'
>>
m=input('Please input the starting mile of the conversion table ');
i=input('Please input the increment between lines in miles (mi) ');
c=input('Now, please enter the number of lines to show in the conversion table ');
g=(m+(i*c));%for calculation issue,calculating the value of mile in the last row after all increamnents
fprintf('Miles Yards Foot ');
for t=m:i:g%running a for loop,loop starts from m and ends to g with a increament of i
fprintf('========================= ');
y=1760*t;%now while calculating we use t instead of m
f=5280*t;%same here, because in each run of this loop the value of t increases
fprintf('%1.2f %1.1f %1.1f ',[t,y,f,]);%replacing m with t
end
>>
then try your previous code and input m=[4 5 6 7 8] and next time put [4,5,6,7,8] . It is recommended to use loops for this type of requirements . If you want to store the values as a matrix then you must use this
>>
m=input('Please input the starting mile of the conversion table ');
i=input('Please input the increment between lines in miles (mi) ');
c=input('Now, please enter the number of lines to show in the conversion table ');
j=1;%defining matrix index number which always start from 1
g=(m+(i*c));%for calculation issue,calculating the value of mile in the last row after all increamnents
fprintf('Miles Yards Foot ');
for t=m:i:g%running a for loop,loop starts from m and ends to g with a increament of i
fprintf('========================= ');
y=1760*t;%now while calculating we use t instead of m
b(j)=y;%making a matrix "b"
j=j+1;
f=5280*t;%same here, because in each run of this loop the value of t increases
fprintf('%1.2f %1.1f %1.1f ',[t,y,f,]);
end
%now you can access any value from matrix b
b(3)
>>
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.