Display Loop Values in a Matrix?
Mostrar comentarios más antiguos
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.
Respuestas (1)
Wayne King
el 26 de Abr. de 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
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!