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

18 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by