How to use find when some of the searches will not return a result?
6 views (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
OCDER
on 10 Oct 2017
Edited: OCDER
on 10 Oct 2017
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 %;
More Answers (1)
Andrei Bobrov
on 10 Oct 2017
Edited: Andrei Bobrov
on 10 Oct 2017
[X, Y] = meshgrid([2.5:5:357.5],[-76:4:80]);
[m n] = size(X);
Z = nan(m,n);
for ii=1:m
for jj=1:n
k = A( A(:,1)==Y(ii,jj) & A(:,2)==X(ii,jj), 3);
if k > 0;
Z(ii,jj) = k;
end
end
end
or
aa = reshape(A,[3,2,1]);
l0 = bsxfun(@eq,Y,aa(:,1,:)) & bsxfun(@eq,X,aa(:,2,:));
l1 = any(l0,3);
Z = sum(bsxfun(@times,l0,aa(:,3:)),3);
Z(~l1) = nan;
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!