How can i create an array whose length indirectly depends on parfor loop's index?

1 回表示 (過去 30 日間)
Bui Tuan
Bui Tuan 2017 年 11 月 29 日
コメント済み: Steven Lord 2017 年 11 月 30 日
As the title says, i want to ask if there is an elegant way to create an array whose length is indirectly related to the index of a parfor loop in a certain way.
The following code lines give me the error "size input must be integers". I'm sure the error is due to me trying to create the zero array K whose length is N (which, unfortunately, indirectly depends on the corresponding index of the parfor loop).
lambda = [10, 70, 20, 15];
parfor i = 1:length(lambda)
N = lambda(i);
K = zeros([1,N]);
end

採用された回答

Edric Ellis
Edric Ellis 2017 年 11 月 30 日
Strange, that code works as written for me, so I'm not sure what's going wrong for you. But even so, I don't think it would do what you wanted - the variable K is a parfor temporary variable. A temporary variable is one which is fully assigned to on each iteration of the loop, and its value is not available after the loop completes.
I suspect that what you wanted was a parfor reduction variable, like so:
output = [];
parfor idx = 1:3
newValues = (1:idx) .* (10 .^ (idx-1));
output = [output, newValues];
end
disp(output)
which results in
1 10 20 100 200 300
Reduction variables like output above allow you to accumulate values - often through concatenation (as shown above), or addition.
  2 件のコメント
Bui Tuan
Bui Tuan 2017 年 11 月 30 日
編集済み: Bui Tuan 2017 年 11 月 30 日
Hi Edric, thank you for your answer. I put the wrong code lines to the question actually. The original ones are something like this:
lambda = 0.1:0.1:1.2;
T = 1000; M = 24;
parfor i = 1:length(lambda)
N = M*T*lambda(i);
K = zeros([1,N]);
end
Also, i have found that the error is NOT caused by parfor, but for some reason the calculated N was NOT an integer. For example, using that code, i get N = 7.2000e+03 (which is not an integer) when lambda(i) = 0.3, instead of 7200 and as a result, the error shows up when i try to create K.
Still, I don't know what is causing N to not be an integer sometime.
Steven Lord
Steven Lord 2017 年 11 月 30 日
You're encountering round-off error.

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

その他の回答 (0 件)

カテゴリ

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