summing elements of an array until a value appears

13 ビュー (過去 30 日間)
Thomas Gvero
Thomas Gvero 2020 年 1 月 29 日
編集済み: Turlough Hughes 2020 年 1 月 29 日
I'm trying to execute a for loop that looks at permutations of a set and sums all the elements until a specific element 'k' is reached.
rather than sum(line(1:k)) i need effectively sum(line(1:'k')) but inputting that exactly doesn't work. Any ideas?
if sum(line(1:k))>=q && (sum(line(1:k))-k)<q
  4 件のコメント
Thomas Gvero
Thomas Gvero 2020 年 1 月 29 日
Sorry I wasn't very clear. I am basically trying to sum every permutation of an array up to and including a particular element (not always the same index each time). For example, if I was summing up to 2, and my permutations were:
1,2,3
1,3,2
2,1,3
then my sums would go up to the number 2 not the second element. The sums would be 3,6,2 repectively.
Thomas Gvero
Thomas Gvero 2020 年 1 月 29 日
this is running in a wider for loop of a function so i need it to output exactly what i need each time which is why i need the second loop

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

採用された回答

Mohammad Sami
Mohammad Sami 2020 年 1 月 29 日
a = [1 1 1 2 3 4 2];
i = find(a==2,1,'first');
if ~isempty(i)
val = sum(a(1:i));
else
val = sum(a);
end

その他の回答 (2 件)

the cyclist
the cyclist 2020 年 1 月 29 日
Here is one way.
% Inputs
inputVector = [5 4 3 2 1];
inputValueToFind = 2;
% Find the location of the index
idxEnd = find(inputVector==inputValueToFind,1);
% Sum up to that index
sum(inputVector(1:idxEnd))

Turlough Hughes
Turlough Hughes 2020 年 1 月 29 日
編集済み: Turlough Hughes 2020 年 1 月 29 日
Say your array is called data:
q=2;
data = [1 2 3; 1 3 2; 2 1 3; 1 0 3; 1 2 2]; % Includes rows without any values = q, and repeated q.
You could then get the cumulative sum of values up to the first occurence of q in each row as follows:
[ ~,k ] = max(data == q,[],2); % Index for first column equal to q in each row.
k(~any(data == q,2)) = 0 % Case for rows that have no values == q.
for c = 1:numel(k)
csums(c,1) = sum( data(c,1:k(c)) );
end
Here, data == q is a logical array of all values in data that are equal to q. Taking the max along each row will return the "first" index for a given row in data being equal to q. The second line accounts for cases where no values are equal to q.

カテゴリ

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

タグ

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by