Grid 2D matrix to xyz

10 views (last 30 days)
karem  Fathy
karem Fathy on 17 Jul 2016
Commented: karem Fathy on 18 Jul 2016
I have file trend.mat as a Grid 2D martix and i am trying to use the following code to convert it to xyz in csv file. where the size (trend)= 180 * 360 which mean each value in trend have xy values but this code has a problem in dimension.
load('trend.mat');
[lon,lat] = size(trend); % matrix dimension must be (y) to latitude, (X) to longitude
tws = trend %(:); % tws is the trend values of water hieght Variation
lon=linspace(0,1,360); %lon=0:360;
lat=linspace(90,-1,-90); %lat=90:-1:-90;
file = fopen('Trend.csv','w');
for y = 1:180
for x = 1:360
fprintf(file, strcat(num2str(lat(y)),',',num2str(lon(x)),','));
for z=1:1
fprintf(file, '%.16g,',tws(x,y,z));
end;
fprintf(file,'\n');
end;
end;
fclose(file);

Accepted Answer

John BG
John BG on 18 Jul 2016
Karem
you have crossed x and y in the fprinf writing to file. Your code corrected:
load trend.mat
[lon,lat] = size(trend); % Where X = 360 & Y = 180 the dimension of matrix
lon=0.5:359.5;
lat=89.5:-1:-89.5;
tws = trend;
file = fopen('Trend.csv','w');
for y = 1 : 180
for x = 1: 360
fprintf(file,strcat(num2str(lat(y)),',',num2str(lon(x)),','));
fprintf(file, '%.16g,',tws(y,x));
fprintf(file,'\n');
end;
end;
fclose(file);
If you find this answer of any help solving your question,
please mark my answer as ACCEPTED ANSWER.
To any other reader, if this answer is found of any interest, please click on the thumbs-up vote link,
thanks in advance
John
  1 Comment
karem  Fathy
karem Fathy on 18 Jul 2016
Hi John It's working, Thanks so much for your help. I appreciate your efforts.

Sign in to comment.

More Answers (1)

Walter Roberson
Walter Roberson on 17 Jul 2016
lat=linspace(90,-1,-90);
would mean that you wanted to have negative 90 points in the range 90 to -1 . You cannot create negative 90 points.
linspace(A,B,N) is for creating N points that run from A to B
You probably want the colon operator, 90 : -1 : -90 and 0 : 1 : 360
  4 Comments
Image Analyst
Image Analyst on 17 Jul 2016
Edited: Image Analyst on 17 Jul 2016
Attach trend.mat so we can try things. Also, explain what "I still have a problem" means exactly.
To format your code so that it looks normal, see this:
karem  Fathy
karem Fathy on 17 Jul 2016
Please find the attached file. I mean with ruining the code, i got an error massage "Index exceeds matrix dimensions".

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!