필터 지우기
필터 지우기

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

조회 수: 3 (최근 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에서 Surface and Mesh Plots에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by