SOS: How do I get the same amount of positive and negative values in a random vector?
조회 수: 1 (최근 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!