Borrar filtros
Borrar filtros

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

3 visualizaciones (últimos 30 días)
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!

Respuesta aceptada

Walter Roberson
Walter Roberson el 24 de Abr. de 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)

Más respuestas (1)

LeoAiE
LeoAiE el 24 de Abr. de 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)

Categorías

Más información sobre Surface and Mesh Plots en Help Center y File Exchange.

Productos


Versión

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by