Storing value in a matrix from a for loop.

7 ビュー (過去 30 日間)
Sophie
Sophie 2025 年 7 月 25 日
編集済み: Torsten 2025 年 7 月 28 日
Hi all, I'm quite new to matlab and coding in general, and I'm having problems getting my code to do what I want it to do. I'm trying to look at 1 lon and lat then for all the next lon and lats check to see if they're a small enough distance apart. I want it then to put all the answers that are within that distance into a row of a matrix then move to the next row once the inner for loop has ended. The problem I'm having is that the output of closeIx is just the entries "i" on a diagonal and zero's everywhere else (an identity matrix). I'm not sure how to make it so it actually put the incecies of the entries that are within that delta tolerance in the row. I'm sorry if its hard to run through without the loaded file, I'm not sure if I can put that in here someway, but let me know if there's any further things I can provided to better understand the question I'm asking. Thanks so much, heres my code:
load trackmat.mat
%File with latitudes and longitudes that are used in the study its 7949 x 1
%double
size = length(Lat);
closeIx = zeros(size,size);
delta = 0.05;
thisIx = 1;
for i = 1:size-1
%current latitude and longitude for particle we're looking at
currlat = Lat(i,1);
currlon = Lon(i,1);
for j = 1+i
%latitude and longitude of the other points the particle goes to other than the current one
nextlat = Lat(j);
nextlon = Lon(j);
difflat = abs((nextlat-currlat));
difflon = abs((nextlon-currlon));
if difflat<delta && difflon<delta
closeIx(i,thisIx) = j;
end
thisIx = thisIx + 1;
end
end

採用された回答

Torsten
Torsten 2025 年 7 月 25 日
編集済み: Torsten 2025 年 7 月 28 日
Don't use "size" as a variable name - it's a MATLAB - reserved function:
Maybe like this ?
Or better a distance matrix d with
d(i,j) = max(abs(Lat(i)-Lat(j)),abs(Lon(i)-Lon(j)))
?
load trackmat.mat
%File with latitudes and longitudes that are used in the study its 7949 x 1
%double
s = numel(Lat);
closeIx = zeros(s);
delta = 0.05;
for i = 1:s-1
%current latitude and longitude for particle we're looking at
currlat = Lat(i);
currlon = Lon(i);
thisIx = 0;
for j = i+1:s
%latitude and longitude of the other points the particle goes to other than the current one
nextlat = Lat(j);
nextlon = Lon(j);
difflat = abs((nextlat-currlat));
difflon = abs((nextlon-currlon));
if difflat<delta && difflon<delta
thisIx = thisIx + 1;
closeIx(i,thisIx) = j;
end
end
end
  1 件のコメント
Sophie
Sophie 2025 年 7 月 28 日
Hi, thanks so much for the answer. That worked in fixing my problem, thank you!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMarine and Underwater Vehicles についてさらに検索

タグ

製品


リリース

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by