Borrar filtros
Borrar filtros

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

2 visualizaciones (últimos 30 días)
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 comentario
Stephen23
Stephen23 el 8 de Oct. de 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:

Iniciar sesión para comentar.

Respuesta aceptada

Matt J
Matt J el 8 de Oct. de 2023
Editada: Matt J el 8 de Oct. de 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);

Más respuestas (0)

Categorías

Más información sobre Get Started with MATLAB en Help Center y File Exchange.

Productos


Versión

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by