Simple MATLAB loop

  • #1
66
7
I have a list of latitudes:
lats =
41.0100000000000
43.7800000000000
44.4200000000000
41.2500000000000
42.8000000000000
42.7500000000000
42.4900000000000
42.4900000000000
42.7800000000000
44.3200000000000
42.1500000000000
41.9300000000000
41.1700000000000

I have a list of gridpoints (latitudes):
X =
41
42
43
44
45
46

I want to subtract every latitude value from my list of grid points... (i.g, X1-lats1, X1-lats2,X3-lats3....etc)

if any X value is greater than any lats value i want d = 0 if not d = 1..


Code i tried..i know why it dosent work but i dont know how to code it >.<
for i = lats
for j = X
if i - j > 3
d = 0;
else
d = 1;
end
end
end
 

Answers and Replies

  • #2
13
2
You probably want something like this:
Matlab:
lats=[41.01  43.78  44.42 41.25 42.80 42.75 42.49 42.49 42.78 44.32 42.15 41.93 41.17];
X=[41:46];
ans=zeros(length(lats),length(X));
for ix0=1:length(lats) for ix1=1:length(X) ans(ix0,ix1)=lats(ix0)-X(ix1); end; end;
So, "ans" will contain your "lats" by "X" differences.
 
  • Like
Likes Tone L
  • #3
13
2
Or, better:
Matlab:
for ix0=1:length(lats) ans(ix0,:)=lats(ix0)-X; end;
 
  • Like
Likes Tone L
  • #4
kreil
Insights Author
Gold Member
668
67
You can do this without using a loop at all by using the bsxfun function. This lets you subtract each value in X from the lats vector, and it forms a matrix. The row C(j,:) is equal to X(j)-lats.

Then you just set all of the negative values (for which the value in X was less than the value in lats) to one, and the other values where X was greater will be 0.

This code should be very fast if you have a larger dataset to do this with.
Code:
C = bsxfun(@minus,X,lats')<0

C =

     1     1     1     1     1     1     1     1     1     1     1     1     1
     0     1     1     0     1     1     1     1     1     1     1     0     0
     0     1     1     0     0     0     0     0     0     1     0     0     0
     0     0     1     0     0     0     0     0     0     1     0     0     0
     0     0     0     0     0     0     0     0     0     0     0     0     0
     0     0     0     0     0     0     0     0     0     0     0     0     0
 

Related Threads on Simple MATLAB loop

  • Last Post
Replies
4
Views
5K
  • Last Post
Replies
6
Views
12K
  • Last Post
Replies
11
Views
3K
Replies
1
Views
4K
Replies
1
Views
3K
Replies
6
Views
2K
  • Last Post
Replies
1
Views
2K
  • Last Post
Replies
2
Views
1K
  • Last Post
Replies
1
Views
804
  • Last Post
Replies
2
Views
3K
Top