Display Loop Values in a Matrix?
34 views (last 30 days)
Show older comments
I have a loop that is supposed to calculate a matrix. Which it does right, but it does not print how I want it too. I show my code and how it prints now.
for y=0:n-1;
Cm=A.^y;
C=Cm(n)*B;
disp(C)
end
Answer
2
2
2
6
6
6
18
18
18
I want the results to display like this
ans =
2 6 18
2 6 18
2 6 18
but no matter what I try I cannot get it to do so. Any help would be greatly appreciated. Thank you.
0 Comments
Answers (1)
Wayne King
on 26 Apr 2012
One way is to just collect the values into a matrix inside the loop and display outside
C = zeros(3,3);
for n = 1:9
C(n) = randi(5,1,1);
end
fprintf('%d\t %d\t %d\n',C);
% or disp(C)
You actually don't need to even set it up as a matrix first:
C = zeros(9,1);
for n = 1:9
C(n) = randi(5,1,1);
end
fprintf('%d\t %d\t %d\n',C);
If you want to print it out in the loop, you can do something like
C = zeros(9,1);
for n = 1:9
C(n) = randi(5,1,1);
if (mod(n,3)~=0)
fprintf('%d \t',C(n));
else
fprintf('%d\n',C(n));
end
end
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!