Contour Plot with Boolean Indices (z must be at least a 2x2 matrix)

5 次查看(过去 30 天)
I'm trying to create a contour plot where the output depends on a condition from the input. An example is shown below.
The code is supposed to assign Z=Y when Y<=5 and Z=X when Y>5.
X = 1:1:5;
Y = 1:1:10;
[X,Y] = meshgrid(X, Y);
bool = Y <= 5;
Z(bool) = Y(bool);
Z(~bool) = X(~bool);
contour(X,Y,Z)
I know that the bool variable is getting initialized correctly, but for some reason, Z becomes a really long vector instead of keeping its dimensions. (which gives the error using contour: Z must be at least a 2x2 matrix)
I'm not sure how to approach this problem differently, so any insight is greatly appreciated.
Thanks!

采纳的回答

Walter Roberson
Walter Roberson 2023-4-24
X = 1:1:5;
Y = 1:1:10;
[X,Y] = meshgrid(X, Y);
Z = X;
bool = Y <= 5;
Z(bool) = Y(bool);
contour(X,Y,Z)

更多回答(1 个)

LeoAiE
LeoAiE 2023-4-24
The issue you're facing is due to the fact that when you use logical indexing with an uninitialized array like Z, MATLAB automatically converts it into a vector. To fix this issue, you can initialize the Z array with the same size as X and Y using the zeros function.
X = 1:1:5;
Y = 1:1:10;
[X,Y] = meshgrid(X, Y);
bool = Y <= 5;
Z = zeros(size(X));
Z(bool) = Y(bool);
Z(~bool) = X(~bool);
contour(X,Y,Z)

类别

Help CenterFile Exchange 中查找有关 Interpolation 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by