フィルターのクリア

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

3 ビュー (過去 30 日間)
Robert Zukowski
Robert Zukowski 2023 年 4 月 24 日
コメント済み: Robert Zukowski 2023 年 4 月 24 日
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 Center および File ExchangeSurface 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