I'm multiplying 2 3x3 matrices and the answer is displaying as a 1x9, how can i fix this?

1 Ansicht (letzte 30 Tage)
A=[0.4 0.1 0.2;0.3 0.7 0.7;0.3 0.2 0.1];
b=[0.4 0.1 0.2;0.3 0.7 0.7;0.3 0.2 0.1];
for i = 1:40
b = A*b;
fprintf('i=%3d b=[',i);
for j = 1:9
fprintf('%12.6f',b(j));
end
fprintf(']\n');
end

Akzeptierte Antwort

Star Strider
Star Strider am 8 Okt. 2018
Your code is printing what you told it to print.
Try this:
A=[0.4 0.1 0.2;0.3 0.7 0.7;0.3 0.2 0.1];
b=[0.4 0.1 0.2;0.3 0.7 0.7;0.3 0.2 0.1];
for i = 1:40
b = A*b;
fprintf('i=%3d b=[',i);
fprintf('%12.6f %12.6f %12.6f\n%12.6f %12.6f %12.6f\n%12.6f %12.6f %12.6f',b');
fprintf(']\n');
end
  2 Kommentare
Terry Poole
Terry Poole am 8 Okt. 2018
That did it!!! Sorry, I'm terribly new to Matlab. I knew it was somthing inside the for loop, I actually tried the %12.6f multiple times to declare the row's/columns it didn't occur to me to remove the J all together, I assumed I needed to declare a new letter to define the answer of A*b to the ith iteration. Thank you so much!!!
Star Strider
Star Strider am 8 Okt. 2018
As always, my pleasure!
No apologies necessary. We were all new to MATLAB (and to programming in general) at one point in our lives. We’re all still learning.
The solution is in understanding how fprintf (and sprintf) intrepret matrix arguments. It’s worthwhile experimenting with it when time permits.
It is quite understandable that you would consider the need to subscript your matrix so it prints the way you want it to, however since you have already defined your matrix, printing it is relatively straightforward.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Mathematics finden Sie in Help Center und File Exchange

Produkte


Version

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by