Filter löschen
Filter löschen

How do I create and store data into a new row after every loop?

6 Ansichten (letzte 30 Tage)
For example:
I am trying to update the old variable matrix but I am getting an error
f = [1 2 3 4];
a = [1 2 3 4 5 6];
old = 0;
for i = 1:length(a)
new = f.*a(i);
old(:,i) = new;
end
I want an old matrix with these values
{1 2 3 4;2 4 6 8;3 6 9 12;4 8 12 16;5 10 15 20; 6 12 18 24}
thank you

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 23 Dez. 2017
To deliberately grow the old matrix, either initialize
old = zeros(length(f),0);
or else do not initialize old at all. With what you are doing now, you are initializing old as having only one row, but then trying to write multiple rows to it.
More efficient would be to initialize the entire matrix
old = zeros(length(f), length(a));
This would not grow the matrix as you went: it would start it out as the proper size.
  3 Kommentare
Walter Roberson
Walter Roberson am 23 Dez. 2017
To get that error, you must be using a very old MATLAB, such as from 2009.
Try
old(:,i) = new .';
Jaydeep Dutta
Jaydeep Dutta am 23 Dez. 2017
I should have mentioned earlier..I'm currently using a Matlab v6.1 My apologies and thats a lesson learned Thank you very much :)

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by