For loop problem.

I am trying to loop my calculations with a long data, but I do something wrong.
size(a)=15 186
for i=1:size(a,1)
bcn(i,:)=abs(a(i,:)-a(i+1,:));
end
The idea is that bcn should equal like that bcn=abs(a(1,1)-a(2,1))+abs(a(1,2)-a(2,2))+abs(a(1,3)-a(2,3))+abs(a(1,4)-a(2,4))+...+abs(a(i,:)-a(i+1),:);
As you can see this is quite extensive procedure. I know that my first column only have 15 entries. But is there any trick to acquire those numbers anyway. Clearly I am interested in the differences between the data.
Cheers! Will appreciate any help!

1 Comment

I actually get the answer anyway. So I kinda already solved. But now I need to know how I can improve the code so I can make difference with any row, not just consequential...

Sign in to comment.

Answers (1)

Stephen23
Stephen23 on 30 Jan 2017
Edited: Stephen23 on 30 Jan 2017
abs(diff(a,1))
and then play around with sum. For example:
>> A = randi(9,5,10)
A =
8 1 7 6 2 3 1 9 1 8
7 4 9 3 6 2 2 5 2 1
5 8 3 5 6 9 9 8 9 9
9 4 9 6 2 3 9 3 5 4
4 2 1 2 2 6 3 3 5 8
>> B = abs(diff(A,1))
B =
1 3 2 3 4 1 1 4 1 7
2 4 6 2 0 7 7 3 7 8
4 4 6 1 4 6 0 5 4 5
5 2 8 4 0 3 6 0 0 4
>> sum(B,1)
ans =
12 13 22 10 8 17 14 12 12 24
>> sum(B,2)
ans =
27
46
39
32

3 Comments

Thanks! you managed to put my code into one line xD
Do you know how can I find difference from different rows? For example row 1 and 3, row 1 and 4, row 3 and 6 etc...
Changing numbers in diff(A,1) not really does what I wanted. So diff(A,2) takes the difference of the difference, which is not really an aim, although it is interesting.
diff(A,1) calculates difference only between adjacent rows.
Stephen23
Stephen23 on 30 Jan 2017
Edited: Stephen23 on 30 Jan 2017
abs(a(1,1)-a(2,1))+abs(a(1,2)-a(2,2))+abs(a(1,3)-a(2,3))+abs(a(1,4)-a(2,4))+...
could be written like this:
sum(abs(diff(A,1)),2)

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 30 Jan 2017

Edited:

on 30 Jan 2017

Community Treasure Hunt

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

Start Hunting!