Ignoring certain matrix entries with surf plot

24 ビュー (過去 30 日間)
Jacob Wilson
Jacob Wilson 2021 年 8 月 9 日
編集済み: Jacob Wilson 2021 年 8 月 9 日
Hi!
I am attempting to plot some data in a matrix using the surf command. Every nonzero elements happens to be padded by zero elements (i.e. the elements and are zero for every nonzero . I'd like to plot a surface of the nonzero elements only, but I have tried a number of things and have not been able to figure out how to exclude the zero elements. For instance, I tried something like
MatrixName(MatrixName==0)=NaN;
Surf(x,y,MatrixName);
but this method ignores all patches contiaining the zero element points and, due to the nature of my matrix, all surface patches are ignored.
Does anyone know how to request that matlab simply ignore zero elements in generating a surface plot?
Sincerely,
Jacob

採用された回答

Dave B
Dave B 2021 年 8 月 9 日
A few solutions come to mind that all take advantage of interpolation, depending on how 'ignore' is interpreted (I used NaN but you could use ==0 in place of isnan(z)):
% some fake data
[x,y] = meshgrid(-5:5,-5:5);
z = 50 - (x.^2 + y.^2);
nexttile
surf(x,y,z)
title('original')
% mark as nans, noting that the neighbor of every non-nan is nan:
z(1:2:end,:)=nan;
z(:,1:2:end)=nan;
nexttile
surf(x,y,z);
title('problem')
% soln 1: interpolate using nearest
badind=isnan(z);
f=scatteredInterpolant(x(~badind),y(~badind),z(~badind),'nearest');
zfixed=z;
zfixed(badind)=f(x(badind),y(badind));
nexttile
surf(x,y,zfixed)
title('soln 1')
% soln 2: interpolate using linear (smoother)
f=scatteredInterpolant(x(~badind),y(~badind),z(~badind),'linear');
zfixed=z;
zfixed(badind)=f(x(badind),y(badind));
nexttile
surf(x,y,zfixed)
title('soln 2')
% soln 3: interpolate to generate 4 values for every non-nan
nexttile
zi = interp2(z);
xi = linspace(x(1),x(end), width(zi));
yi = linspace(y(1),y(end), height(zi));
surf(xi,yi,interp2(z,'nearest'))
title('soln 3')
  1 件のコメント
Jacob Wilson
Jacob Wilson 2021 年 8 月 9 日
編集済み: Jacob Wilson 2021 年 8 月 9 日
This is exactly what I was looking for. I didn't realize that MATLAB had such an interpolation feature for scattered data. Very cool!
Thanks so much for the solution and the care taken in presenting it.

サインインしてコメントする。

その他の回答 (1 件)

darova
darova 2021 年 8 月 9 日
Don't use '==' equal sign for comparing double numbers
ii = abs(MatrixName-0)<0.1; % precision
MatrixName(ii) = NaN;
  1 件のコメント
Jacob Wilson
Jacob Wilson 2021 年 8 月 9 日
Thank you for this tip; I'll try and remember that!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeSurface and Mesh Plots についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by