Display Loop Values in a Matrix?

3 次查看(过去 30 天)
Alex
Alex 2012-4-26
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.

回答(1 个)

Wayne King
Wayne King 2012-4-26
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

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by