SOS: How do I get the same amount of positive and negative values in a random vector?
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Steven Lord
2020-9-27
编辑:Steven Lord
2020-9-27
% 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 个评论
Rik
2020-9-27
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;
更多回答(1 个)
Rik
2020-9-26
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 个评论
Rik
2020-9-27
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]
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Annotations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!