MATLAB: How to use find when some of the searches will not return a result

findMATLAB

I have some grid data stored in Excel file and I am trying to reformat them into grid data. Below is my code:
A = xlsread('Name.xlsx', 'Feb');
% 3 column data of Latitutde, Longitude, and Variable.
[X, Y] = meshgrid([2.5:5:357.5],[-76:4:80]);
[m n] = size(X);
for i=1:m;
for j=1:n;
if A( A(:,1)==Y(i,j), A(:,2)==X(i,j), 3) > 0;
Z(i,j) = A( A(:,1)==Y(i,j), A(:,2)==X(i,j), 3);
else
Z(i,j) = NaN;
end;
end
end;
I am getting an "Index exceeds matrix dimensions" error. Clearly, some of the search are not supposed to retrieve results. How do I program it, so that it will automatically assign an NaN value, when index exceeds matrix dimensions?
Thanks.

Best Answer

A is a Mx3 matrix, but you are trying to access A as a MxNx3 matrix, ex:
A( A(:,1)==Y(i,j), A(:,2)==X(i,j), 3) %A is not a 3D matrix, exceed dimension
Did you want A(C1&C2, 3), where C1 and C2 are 2 conditions that must be met? See code below with comments:
A = xlsread('Name.xlsx', 'Feb');
% 3 column data of Latitutde, Longitude, and Variable.
[X, Y] = meshgrid([2.5:5:357.5],[-76:4:80]);
Z = NaN(size(X)); %Preallocate Z, otherwise it gets REALLY slow
[m, n] = size(X);
for i=1:m %; Don't need semicolon
for j=1:n %;


C1 = A(:,1)==Y(i,j); %pulling this out for readability and to prevent doing this 2 times
C2 = A(:,2)==X(i,j);
C = C1 & C2; %is this what you want? Must match conditions C1 and C2
if A(C, 3) > 0 %FIX ERROR HERE?
Z(i,j) = A(C, 3); %Is this what you want?
% else %Don't need this anymore, since you initialized Z as NaN
% Z(i,j) = NaN;
end %;
end
end %;
Related Question