Convert x y coordinates and z data to Matrix

조회 수: 37 (최근 30일)
user20912
user20912 2022년 9월 15일
답변: Robert Daly 2023년 8월 11일
I have three vectors
>> whos x y VAR1
Name Size Bytes Class Attributes
x 21242x1 679744 double
y 21242x1 679744 double
var1 21242x1 679744 double
where X and Y represent the location of the corresponding value of var1. What Im trying to do is to convert all this data to a matrix.
What I've done until now is:
a1 = 21242;
m = zeros(a1,a1).*NaN;
indexes = sub2ind([a1,a1],x,y);
m(indexes) = var1
Based on this question but I'm getting an error
Error using sub2ind (line 43)
Out of range subscript.
Which, according to another question about this error, is because I'm trying access elements which does not exist on the matrix.
Any help?
Thanks!
  댓글 수: 5
user20912
user20912 2022년 9월 15일
Thank for the input. However, it's still not working.
I have tried to element by element with a for cycle:
for i1=1:a1
indexes = sub2ind([a1 a1], abs(x(i1)), y(i1));
i1
end
and the problem is in the element 3897:
>> x(3896:3898)
-1.0021
-0.9993
-1.0026
what's the problem with that numbers? I can not find the reason why keep failing.
Dyuman Joshi
Dyuman Joshi 2022년 9월 15일
Indices should also be integers as well.

댓글을 달려면 로그인하십시오.

채택된 답변

Star Strider
Star Strider 2022년 9월 15일
It would help to have the actual vectors.
It may be possible to use the reshape function to create matrices from the vectors, if the vectors are from a gridded original matrix. The easiest way to determine the dimensions of the arrays is to use the unique function and look at the second output. The elements of the second output should be regularly-spaced, and that difference is one dimension to specify in the reshape call, with the other one left as the empty vector [].
Otherwise, use linspace, ndgrid and griddata to create appropriate matrices from scattered data.
.
  댓글 수: 6
user20912
user20912 2022년 9월 19일
Thank you!
This was helpfull to do what I needed to do.
Star Strider
Star Strider 2022년 9월 19일
As always, my pleasure!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Robert Daly
Robert Daly 2023년 8월 11일
I would use interpolation to convert to a regular grid.
scatteredInterpolant is the funtion to do this with your irregularly spaced data.
[X,Y] = meshgrid(linspace(min(x),max(x),500),linspace(min(y),max(y),500));% make 500x500 grid
f = scatteredInterpolant(x,y,var1); % set up the interpolater with your data
Grid_Var1 = f(X,Y); % Do the interpolation onto the grid set up above

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by