How to make for loop for subtraction among consecutive array elements ???

10 ビュー (過去 30 日間)
Ahmad Bilal
Ahmad Bilal 2018 年 4 月 9 日
編集済み: Stephen23 2019 年 6 月 21 日
Hi , I have one question regarding loop. Let us suppose I have an array a =[2 3 1 8 5 6] Now i want to make a for loop such as in each iteration it proceeds as follows: 1st iteration: 2-3, 2-1,2-8,2-5,2-6.
2nd Iteration: 3-2,3-1,3-8,3-5,3-6 and same as for other iterations.
Can anybody help me out with code snippet for such iterations using for loop. Thanks

回答 (1 件)

Navdha Agarwal
Navdha Agarwal 2019 年 6 月 21 日
Following is the code snippet for the iterations using the for loop.
a =[2 3 1 8 5 6];
len = length(a); % length of the array, here 6
answer = zeros(len,len-1);
for i = 1:len
index = 1;
for j = 1:len
if(i~=j)
answer(i,index) = a(i)-a(j);
index = index+1;
end
end
end
disp(answer)
For this question, the answer is stored in the matrix of dimentions 6x5. This is because there are 6 elements and for each element, there will be 5 iterations in its row.
I hope this is helpful.
  1 件のコメント
Stephen23
Stephen23 2019 年 6 月 21 日
編集済み: Stephen23 2019 年 6 月 21 日
It is much simpler to avoid loops (each column is one "iteration"):
>> a = [2,3,1,8,5,6];
>> m = a(:)-a % or use BSXFUN for version before R2016b.
m =
0 -1 1 -6 -3 -4
1 0 2 -5 -2 -3
-1 -2 0 -7 -4 -5
6 5 7 0 3 2
3 2 4 -3 0 -1
4 3 5 -2 1 0
And optionally remove the diagonal zeros:
>> n = numel(a);
>> m(1:1+n:end) = [];
>> m = reshape(m,[],n)
m =
1 -1 1 -6 -3 -4
-1 -2 2 -5 -2 -3
6 5 7 -7 -4 -5
3 2 4 -3 3 2
4 3 5 -2 1 -1

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

カテゴリ

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