SOS: How do I get the same amount of positive and negative values in a random vector?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
MadjeKoe
el 26 de Sept. de 2020
Comentada: Rik
el 27 de Sept. de 2020
I'm a beginner with matlab. I need to make a plot with 2 vectors with both 200 values between -1 and 1. Then I need to select the points with both x & y above 0 and plot this. I tried this:
a = -1;
b = 1;
x = (b-a)*rand(200,1) + a;
y = (b-a)*rand(200,1) + a;
minx = x(x>0);
miny = y(y>0);
plot(minx,miny)
I get the notification that my vectors have different lengths. I think this is because there are not the same amount of negative & positive values. Does anyone know how I can fix this? I've been stuck at it for a really long time.
0 comentarios
Respuesta aceptada
Steven Lord
el 27 de Sept. de 2020
Editada: Steven Lord
el 27 de Sept. de 2020
% Generate sample data
x = randn(1, 50);
y = randn(1, 50);
% Determine where positive and negative values occur in each
xpos = x > 0;
ypos = y > 0;
hold on
% Plot data in quadrant 1 (x positive, y positive) as red circles
xposANDypos = xpos & ypos;
plot(x(xposANDypos), y(xposANDypos), 'ro')
% Plot data in quadrant 4 (x positive, y negative) as green pluses
xposANDyneg = xpos & ~ypos;
plot(x(xposANDyneg), y(xposANDyneg), 'g+')
% Plot data in quadrant 2 (x negative, y positive) as blue triangles
xnegANDypos = ~xpos & ypos;
plot(x(xnegANDypos), y(xnegANDypos), 'b^')
% Plot data in quadrant 3 (x negative, y negative) as black stars
xnegANDyneg = ~xpos & ~ypos;
plot(x(xnegANDyneg), y(xnegANDyneg), 'k*')
% Draw the lines betwen the quadrants
ax = gca;
ax.XAxisLocation = 'origin';
ax.YAxisLocation = 'origin';
You may ask what if x or y contains an actual 0. The chances of a point in x or y being exactly zero is miniscule so I'm ignoring it for purposes of this example. Some points may be drawn on top of the axes lines, but if you look at those points with data tips they are in the correct quadrant for their symbol.
2 comentarios
Rik
el 27 de Sept. de 2020
If you want to keep the normal distrubution you can't.
What you can do is use the exact same strategy to set a value in your vectors.
x(x<-1)=-1;
Más respuestas (1)
Rik
el 26 de Sept. de 2020
Your question differs from your description. If you want to select the points with both x and y above 0, you need to use both as a condition. See this example:
a=[1 5 3 8 40 3];
b=[6 4 2 1 56 2];
clc
L1= a>7
L2= b<5
L=L1&L2
2 comentarios
Rik
el 27 de Sept. de 2020
Technically those are not 1 and 0, but true and false. If you want the actual value you need to use it as index:
A = [2 3 87 1];
A([false true false true]) % returns [3 1]
Ver también
Categorías
Más información sobre Annotations en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!