Display Loop Values in a Matrix?

3 vues (au cours des 30 derniers jours)
Alex
Alex le 26 Avr 2012
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.

Réponses (1)

Wayne King
Wayne King le 26 Avr 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

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by