Display Loop Values in a Matrix?

13 ビュー (過去 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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by