How to make for loop for subtraction among consecutive array elements ???
11 views (last 30 days)
Show older comments
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
0 Comments
Answers (1)
Navdha Agarwal
on 21 Jun 2019
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 Comment
Stephen23
on 21 Jun 2019
Edited: Stephen23
on 21 Jun 2019
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
See Also
Categories
Find more on Multidimensional Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!