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

2 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2023-10-8
"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:

请先登录,再进行评论。

采纳的回答

Matt J
Matt J 2023-10-8
编辑:Matt J 2023-10-8
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);

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Get Started with MATLAB 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by