フィルターのクリア

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

2 ビュー (過去 30 日間)
richard
richard 2023 年 10 月 8 日
コメント済み: Stephen23 2023 年 10 月 8 日
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 Center および File ExchangeGet 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