Calculate values inside a nested loop with different steps and store them in the same variable.

10 ビュー (過去 30 日間)
I have a matrix (x) and want to calculate where its values are above certain thresholds and store the results in a new matrix (C). To be more specific, I need to check whether the condition sum(x>i) is met in 18 different values of i (classes). My difficulty is that I want a different step so for the first ten values step=1, while the remaining 8 while have step=5. I tried a nested loop but the result was not the expected. Any ideas how to proceed?
for i=1:10
C(i)= sum(x>i);
for j=15:5:50
C(j)= sum(x>j);
end
end

採用された回答

Stephen23
Stephen23 2022 年 12 月 16 日
編集済み: Stephen23 2022 年 12 月 16 日
Assuming that SUM() returns a scalar:
V = [1:10,15:5:50];
C = V; % preallocate
for k = 1:numel(V) % loop over indices, not your data values
C(k) = sum(x>V(k));
end
Note that in MATLAB it is almost always easier to iterate over indices, rather than over data values.
Or alternatively:
C = arrayfun(@(v)sum(x>v), V)

その他の回答 (1 件)

Jiri Hajek
Jiri Hajek 2022 年 12 月 8 日
Hi, you can use any special vector of indexes (natual numbers) like this:
j = [1:10,15:5:50];
for i=j
C(i)= sum(x>i);
end
  10 件のコメント
Ancalagon8
Ancalagon8 2022 年 12 月 16 日
編集済み: Ancalagon8 2022 年 12 月 17 日
One option is to use nonzeros, but what if a value that I need is zero?
Stephen23
Stephen23 2022 年 12 月 16 日
編集済み: Stephen23 2022 年 12 月 16 日
"your answer does not help me understand why I receive 50 values instead of 18"
Basically you are doing this:
A(50) = pi
A = 1×50
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
How many elements do you expect an array to have, when you assign something to its 50th element?
"One option is to use nonzeros, but whati if a value that I need is zero?"
As I wrote earlier, just actual indices for indexing, not your data values.

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

カテゴリ

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