MATLAB Solving MATLAB Loop with X & Latitudes

AI Thread Summary
The discussion focuses on a coding problem involving the subtraction of a list of latitude values from a set of grid points. The goal is to determine if each grid point is greater than the latitude values, resulting in a binary output where 'd' equals 0 if the grid point is greater and 1 otherwise. The initial code provided does not function as intended, prompting suggestions for improvement. A more efficient approach is proposed using matrix operations, specifically leveraging the bsxfun function to perform the subtraction without explicit loops. This method allows for the creation of a matrix that indicates which grid points are greater than the latitude values, optimizing performance for larger datasets. The final output is a binary matrix where values indicate the comparison results.
Tone L
Messages
72
Reaction score
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 don't know how to code it >.<
for i = lats
for j = X
if i - j > 3
d = 0;
else
d = 1;
end
end
end
 
Physics news on Phys.org
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
Or, better:
Matlab:
for ix0=1:length(lats) ans(ix0,:)=lats(ix0)-X; end;
 
  • Like
Likes Tone L
You can do this without using a loop at all by using the bsxfun function. This let's 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
 
Back
Top