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

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개)

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

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

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2018년 4월 9일

편집:

2019년 6월 21일

Community Treasure Hunt

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

Start Hunting!

Translated by