What is the problem in my for loops?

1 view (last 30 days)
alexander wong
alexander wong on 23 Jun 2021
Commented: Scott MacKenzie 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', 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
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]);
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

Sign in to comment.

Answers (2)

KSSV
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
alexander wong
alexander wong on 23 Jun 2021
Do you know how to solve this problem?
Walter Roberson
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.

Sign in to comment.


Scott MacKenzie
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
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. :)

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!