Change Array Name In Each Loop

19 ビュー (過去 30 日間)
Matthew
Matthew 2017 年 10 月 9 日
コメント済み: Matthew 2017 年 10 月 9 日
I'm writing a For loop and want to create an array each loop, with the name changed according to the loop counter; e.g., Coll1, Coll2, Coll3, etc. Before folks slaughter me for asking...I've already read on here where folks have asked the question and "experts" recoil sharply against them saying it's a very bad newbie idea. Instead they should use the same array name but use indexing. I get that. But in this case I don't think I can do that because in each iteration of the loop, the newly created array has different dimensions each time. So I don't want the largest one creating a slew of zero cells in the smaller ones just for the sake of using a single array name. Any tips on how I can do this?
Thanks in advance, M Ridzon
  2 件のコメント
per isakson
per isakson 2017 年 10 月 9 日
編集済み: per isakson 2017 年 10 月 9 日
Possibilities
  1. Assign "newly created array has different dimensions each time" to a new cell in a cell array
  2. Assign each array to a new field in a structure. Better alternative if you have descriptive names for the arrays. Its easier to remember good names than numbers. Your code will be easier to read.
If you present good reasons for not using one of these two, I will answer questions on eval.
Matthew
Matthew 2017 年 10 月 9 日
#1 sounds like a great idea. I hadn't thought of that. Thanks!

サインインしてコメントする。

採用された回答

Steven Lord
Steven Lord 2017 年 10 月 9 日
As per suggested, use a cell array.
C = cell(1, 10);
for n = 1:10
C{n} = rand(n); % size(C{n}) is [n n]
end
Each cell in C has a different sized matrix.
  1 件のコメント
Matthew
Matthew 2017 年 10 月 9 日
I didn't think of this. Great idea! Thanks!

サインインしてコメントする。

その他の回答 (1 件)

Image Analyst
Image Analyst 2017 年 10 月 9 日
So? Simply have 3 for loops and create a new array in each one. What's the problem?
for k = 1 : whatever1
Coll1(k) = whatever2;
end
for k = 1 : whatever3
Coll2(k) = whatever4;
end
for k = 1 : whatever5
Coll3(k) = whatever6;
end
There's absolutely nothing wrong with that - no shame. Just go ahead and do it.
  1 件のコメント
Matthew
Matthew 2017 年 10 月 9 日
Thanks, but this won't work. I do not know beforehand how many times FOR will run; i.e., the ending iteration changes. Therefore, Coll<end#> is unknown.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by