Effacer les filtres
Effacer les filtres

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

2 vues (au cours des 30 derniers jours)
richard
richard le 8 Oct 2023
Commenté : Stephen23 le 8 Oct 2023
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 commentaire
Stephen23
Stephen23 le 8 Oct 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:

Connectez-vous pour commenter.

Réponse acceptée

Matt J
Matt J le 8 Oct 2023
Modifié(e) : Matt J le 8 Oct 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);

Plus de réponses (0)

Catégories

En savoir plus sur Get Started with MATLAB dans Help Center et File Exchange

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by