for loop starting from 1

8 ビュー (過去 30 日間)
Morten Jørgensen
Morten Jørgensen 2019 年 4 月 11 日
編集済み: Bob Thompson 2019 年 4 月 11 日
Hi
Is there a way to make this start from 1, when 1 is not in Player{4,1}(:,1)?
i want to take the sum from 1:127, 127:162, 162:285 and so on, is this possible?
thanks
% Player{2,1}(:,2) is a vector with a length of 590
% Player{4,1}(:,1) =
127
162
285
300
316
323
493
500
584
for j = 1:length(Player{4,1})-1
Output(j,1) = sum(Player{2,1}(Player{4,1}(j,1):Player{4,1}(j+1,1),2))
end
  3 件のコメント
Morten Jørgensen
Morten Jørgensen 2019 年 4 月 11 日
thanks.
the first number of a is 127, but i want to make it start from1 instead of 127.
would it be easier to just alter the vector a to:
1
127
162
285
300
316
323
493
500
584
so i get the sum of b 1:127 in the first ?
Bob Thompson
Bob Thompson 2019 年 4 月 11 日
Yes, it would be easier to make that modification. Because you are only looking to use 1 initially, it would be possible to add that as a boundary with an if statement, but that is making things much more complicated than simply changing 'a'.

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

回答 (1 件)

Jan
Jan 2019 年 4 月 11 日
a = Player{4,1}(:, 1);
b = Player{2,1}(:, 2);
Output = zeros(length(a)-1, 1); % Pre-allocate
Output(1) = sum(b(1:a(j+1)));
for j = 2:length(a)-1
Output(j) = sum(b(a(j):a(j+1)));
end
Or
Output = zeros(length(a)-1, 1); % Pre-allocate
a(1) = 1;
for j = 1:length(a)-1
Output(j) = sum(b(a(j):a(j+1)));
end
  1 件のコメント
Bob Thompson
Bob Thompson 2019 年 4 月 11 日
編集済み: Bob Thompson 2019 年 4 月 11 日
Wouldn't using a(1) = 1; remove the current value of a(1) = 127? I would think that this would mean that Output(1) would end up spanning from 1:162, instead of 1:127. I would think you would need to concat instead.
a = Player{4,1}(:, 1);
a = [1; a];

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

カテゴリ

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