What is the problem in my for loops?
1 view (last 30 days)
Show older comments
function tabulatedata()
m = input('Enter m: ');
n = input('Enter n: ');
p = input('Enter p: ');
fprintf('\nColumn 1\Column 2\n');
for i = 0:n:m
for j = 0:m/n
a = (2.^(j))*p;
fprintf('%3.2f\t\t\t', i);
fprintf('%3.2f\n', a);
end
end
end
We input m = 12, n = 2, p=100
Output:
Column1 Column 2
0.00 100.00
2.00 200.00
4.00 400.00
6.00 800.00
8.00 1600.00
10.00 3200.00
12.00 6400.00
I cannot get the correct output.
1 Comment
Stephen23
on 23 Jun 2021
You don't need any loops:
m = 12;
n = 2;
p = 100;
v = 0:n:m;
a = 2.^(v./2)*p;
fprintf('%3.2f\t\t\t%3.2f\n', [v;a]);
Answers (2)
KSSV
on 23 Jun 2021
function tabulatedata()
m = input('Enter m: ');
n = input('Enter n: ');
p = input('Enter p: ');
fprintf('\nColumn 1\Column 2\n');
for i = 0:n:m
for j = 0:m/n
a = (2.^(j))*p;
fprintf('%3.2f\t\t\t %3.2f\n', i,a);
end
end
end
5 Comments
Walter Roberson
on 23 Jun 2021
What problem? You said you do not get the right output, but you do not tell us what output you expect instead.
Scott MacKenzie
on 23 Jun 2021
You don't need nested loops:
m = 12;
n = 2;
p = 100;
fprintf('\nColumn 1\t\tColumn 2\n');
for i = 0:n:m
a = 2.^(i/2)*p;
fprintf('%3.2f\t\t\t', i);
fprintf('%3.2f\n', a);
end
Output:
Column 1 Column 2
0.00 100.00
2.00 200.00
4.00 400.00
6.00 800.00
8.00 1600.00
10.00 3200.00
12.00 6400.00
2 Comments
Scott MacKenzie
on 23 Jun 2021
You're welcome. BTW @Stephen Cobeldick's answer is clearly better. Feel free to unaccept my answer and choose @Stephen Cobeldick's answer. I won't take offence. :)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!