Calculate values inside a loop and store them in variables.
12 ビュー (過去 30 日間)
古いコメントを表示
I have a matrix and want to calculate where its values are above certain thresholds and store the results in a new matrix. My difficulty is that I want a different step, I tried a nested loop but the result was not the expected. Any ideas how to proceed?
0 件のコメント
採用された回答
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)
0 件のコメント
その他の回答 (1 件)
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
6 件のコメント
Steven Lord
2022 年 12 月 15 日
Let's take a smaller example, one where we can view the vector without scrolling.
indicesToAssignTo = [1 3 5]
for whichInd = indicesToAssignTo
x(whichInd) = whichInd.^2
end
When I run this you see that MATLAB displays x three times, once for each assignment to x inside the loop.
In the first iteration x is a 1-by-1 because we assign to element number 1.
In the second iteration x is a 1-by-3 because we assign to element number 3. MATLAB can't just leave element 2 empty, so it fills it with a default fill value of 0.
In the third iteration x is a 1-by-5 because we assign to element number 5. Again MATLAB can't just leave element 4 empty, so it fills it with 0.
In your code your vector has 50 elements because you assign to element number 50. MATLAB can't leave the elements to which you don't assign empty so it fills them with 0.
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
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 Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!