How to remove a single point from meshgrid?
9 views (last 30 days)
Show older comments
I have written this code and want to model the temperature profile. I want to exclude (0,0) from the meshgrid as the function becomes infinite there. How can I do that?
x = linspace(-3,10);
y = linspace(-3,0);
zero_x_idx = find(x == 0);
zero_y_idx = find(y == 0);
% Exclude the point (0, 0) from the arrays
x = x([1:zero_x_idx-1, zero_x_idx+1:end]);
y = y([1:zero_y_idx-1, zero_y_idx+1:end]);
[X,Y] = meshgrid(x,y);
Z=(P_l*exp(-v(sqrt((X.*10^(-3)).^2 + (Y.*10^(-3)).^2) + (X.*10^(-3)))/(2*a)))/(4*3.14*k*sqrt((X.*10^(-3)).^2 + (Y.*10^(-3)).^2))+T0;
1 Comment
Answers (2)
Star Strider
on 31 Jul 2023
I would use ‘logical indexing’ to simply delete that point —
x = linspace(-3,10)
y = linspace(-3,0)
x = x(x~=0)
y = y(y~=0)
Another option would be to replace it with something small, however not zero —
x = linspace(-3,10)
y = linspace(-3,0)
x(x==0) = NaN
y(y==0) = NaN
x = fillmissing(x, 'nearest')
y = fillmissing(y, 'nearest')
The second approach sets the zero value equal to NaN, and then interpolates it with the nearest (most likely non-zero) value.
.
4 Comments
Voss
on 31 Jul 2023
First, notice that zero doesn't appear in x:
x = linspace(-3,10);
zero_x_idx = find(x == 0);
zero_x_idx
But if you used different endpoints or a different number of points in linspace, zero might appear:
x = linspace(-3,10,131);
zero_x_idx = find(x == 0);
zero_x_idx
So, I'm going to go with that.
(Zero does appear in y):
y = linspace(-3,0);
zero_y_idx = find(y == 0);
zero_y_idx
Second, notice that removing the 0 from x and the 0 from y before using them in meshgrid removes not only the point (0,0) but also the lines x=0 and y=0 from the X and Y matrices returned by meshgrid. In other words, you'll have the situation where X and Y don't have any points where X is 0 or Y is 0, instead of the situation where X and Y don't have any points where X is 0 and Y is 0. (I'm sure you've noticed this already but were not sure how to remove a single point instead of both lines, hence the question.)
Here's one way to remove the single point (0,0) from X and Y:
[X,Y] = meshgrid(x,y);
% note: X,Y includes (0,0) at this point in the code:
[r0,c0] = find(X == 0 & Y == 0)
% create a logical matrix of which points to keep:
to_keep = true(size(X));
% set the element at zero_y_idx,zero_x_idx to false:
to_keep(zero_y_idx,zero_x_idx) = false;
% only keep the points in X and Y where to_keep is true:
X = X(to_keep);
Y = Y(to_keep);
% sanity check: that (0,0) is gone
[r0,c0] = find(X == 0 & Y == 0)
2 Comments
Torsten
on 31 Jul 2023
Maybe we could tell, but - as you can imagine - it's difficult without your code :-)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!