how to add elements to an array in a for loop

8 ビュー (過去 30 日間)
Irene Johns
Irene Johns 2021 年 9 月 19 日
回答済み: Stephen23 2021 年 9 月 19 日
Let's say there's an array sample= [ 2 4 5 6 3]
I want to make a function where we get the sum of all the elements greater than 5. so for this example it would be 5+6= 11.
I thought of doing a for loop to check if the elements are greater than 5, then create a new array with all the numbers which are greater than 5 and then use sum(sample). However, I'm not sure how make a new array.
for k= 1:numel(sample)
if samples(k) >=5
%need to make an a new array with all the elements greater than 5 from
%sample array
end
end

回答 (1 件)

Stephen23
Stephen23 2021 年 9 月 19 日
The MATLAB approach is to use logical indexing, not a loop:
V = [2,4,5,6,3];
N = sum(V(V>=5))
N = 11

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by