creating loop with two variables

For example;
a=0:2:10;
b=0:2:6;
% number of elements of a is always bigger than b
I need to create for loop as below;
result(1)=a(1)-b(1);
result(2)=a(2)-b(2);
result(3)=a(3)-b(3);
result(4)=a(4)-b(4);
result(5)=a(5)-b(4);
result(6)=a(6)-b(4);
Since a and b variables' number isn't constant for each problem. How can I create this loop for working properly with arbitrary numbers of a and b?

 採用された回答

Birdman
Birdman 2017 年 12 月 7 日
編集済み: Birdman 2017 年 12 月 7 日

1 投票

for i=1:max(numel(a),numel(b))
if(i>=min(numel(a),numel(b)))
result(i)=a(i)-b(min(numel(a),numel(b)));
else
result(i)=a(i)-b(i);
end
end

3 件のコメント

Stephen23
Stephen23 2017 年 12 月 7 日
Seven lines of code... see my answer for a simpler solution.
Birdman
Birdman 2017 年 12 月 7 日
Your answer is of course simpler but he mentioned to do it with a for loop, therefore I wrote this. Otherwise of course I would have written something like you did.
KL
KL 2017 年 12 月 7 日
You could call numel, outside the loop and store its output in a variable (after finding min and max) and only use this variable inside the loop.
Now, you're calling min and numel so many times (sometimes even twice within the same iteration).

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

その他の回答 (2 件)

Stephen23
Stephen23 2017 年 12 月 7 日
編集済み: Stephen23 2017 年 12 月 7 日

2 投票

Why waste time writing an ugly loop? Here is a simpler solution in just two lines:
>> a = 0:2:10;
>> b = 0:2:6;
>> v = 1:max(numel(a),numel(b));
>> a(min(v,end))-b(min(end,v))
ans =
0 0 0 0 2 4
Jan
Jan 2017 年 12 月 7 日

0 投票

% number of elements of a is always bigger than b
This was not considered in the other suggestions. Another solution:
a = 0:2:10;
b = 0:2:6;
result = a - b(min(1:numel(a), numel(b)))

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

質問済み:

2017 年 12 月 7 日

回答済み:

Jan
2017 年 12 月 7 日

Community Treasure Hunt

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

Start Hunting!

Translated by