# Loop Code Through Each Row of Excel Spreadsheet and Save Result Matrix

2 views (last 30 days)
CMatlabWold on 27 Feb 2023
Edited: M.B on 8 Aug 2023
I haven't been on MATLAB for a while. I suppose I am very rusty. But I have a spreadsheet, and there are two columns of interest: one is labeled x_coord and the other is labeled y_coord. For each row of both columns, I am converting the x and y coordinate values to longitude and latitude degree values. Then, I am writing the results in a matrix. However, it is just not working. I am looking to have a pair of latitude and longitude values for each row, based on the x and y cooredinates. I'd greatly appreciate any help.
N=[];
for K = 1:172
X = data(:,ismember(data.Properties.VariableNames, {'x_coord'}))
Y = data(:,ismember(data.Properties.VariableNames, {'y_coord'}))
info = shapeinfo('ZIP_CODE_040114.shp');
proj = info.CoordinateReferenceSystem;
[lat,lon] = projinv(proj,X{i,1},Y{i,1});
outdata = [lat,lon]
N = [N; outdata]
end
writematrix(N, 'LongLat.csv',"WriteMode","append")

Cris LaPierre on 27 Feb 2023
You don't need a loop. Perform the calculation on the entire column at once.
info = shapeinfo('ZIP_CODE_040114.shp');
proj = info.CoordinateReferenceSystem;
[lat,lon] = projinv(proj,data.x_coord,data.y_coord);
N = [lat,lon]
writematrix(N, 'LongLat.csv',"WriteMode","append")
CMatlabWold on 28 Feb 2023
It is working - Thank you!

M.B on 27 Feb 2023
Edited: M.B on 8 Aug 2023
The issue is with your indexing. You declare K as the index and use i inside the loop.
I agree with Cris, you don't need a loop. The function "projinv" takes vectors as inputs. If you insist on using a loop, you can try the following:
% place all fixed parameters outside the loop
N=nan(172, 2);
X = data(:,ismember(data.Properties.VariableNames, {'x_coord'}));
Y = data(:,ismember(data.Properties.VariableNames, {'y_coord'}));
info = shapeinfo('ZIP_CODE_040114.shp');
proj = info.CoordinateReferenceSystem;
for K = 1:172
[lat,lon] = projinv(proj,X(K),Y(K));
outdata = [lat,lon];
N(K, :) = outdata;
end
writematrix(N, 'LongLat.csv',"WriteMode","append");
CMatlabWold on 28 Feb 2023
Thanks!

### Categories

Find more on Spreadsheets in Help Center and File Exchange

R2022b

### Community Treasure Hunt

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

Start Hunting!