Azzera filtri
Azzera filtri

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

3 visualizzazioni (ultimi 30 giorni)
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!

Risposta accettata

Walter Roberson
Walter Roberson il 24 Apr 2023
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)

Più risposte (1)

LeoAiE
LeoAiE il 24 Apr 2023
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)

Prodotti


Release

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by