Declaring a matrix with null dimension, or checking if a matrix exists

2 Ansichten (letzte 30 Tage)
Inside a for loop, I want to do a calculation that produces new results, and then append these results to an existing matrix called "my_matrix":
for k=1:big_number
new_results = func(blah blah blah)
my_matrix = [my_matrix new_results];
end
The problem is: the first time the calculations are done, "my_matrix" does not exist, so I get an error in Matlab.
--> Is there a way to declare "my_matrix" with no dimensions, so that I don't get the above error on the first loop iteration?
--> Is there a way to check if a matrix called "my_matrix" exists? For instance:
If "my_matrix" exists, then my_matrix = [my_matrix new_results];
If "my_matrix" does NOT exist, then my_matrix = new_results;
  1 Kommentar
Stephen23
Stephen23 am 8 Okt. 2023
"Is there a way to declare "my_matrix" with no dimensions, so that I don't get the above error on the first loop iteration?"
There is nothing stopping you from declaring a matrix to have any of its dimensions to have zero size, e.g.:
M = nan(2,0,3,0);
but probably all you need is this:
M = [];
"Is there a way to check if a matrix called "my_matrix" exists?"
You could use EXIST, but coding using EXIST is slow and best avoided:
Really, that approach is best avoided. Here is a much better approach:
M = func(blah blah blah);
for k = 2:big_number
R = func(blah blah blah)
M = [M,R];
end
However this is all rather moot, because if your code iterates up to a BIG_NUMBER then you really need to preallocate the entire array before the loop:

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Matt J
Matt J am 8 Okt. 2023
Bearbeitet: Matt J am 8 Okt. 2023
There is, but it is highly inadvisable to iteratively grow a matrix like you are doing. Here is one alternative:
my_matrix=cell(1,big_number);
for k=1:big_number
my_matrix{k} = func(blah blah blah);
end
my_matrix=cell2mat(my_matrix);

Weitere Antworten (0)

Kategorien

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

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by