Split a matrix into a two submatrixes by a condition

조회 수: 4 (최근 30일)
Gino Franco
Gino Franco 2014년 10월 2일
편집: Mohammad Abouali 2014년 10월 7일
Let "ex3" a matrix with an arbitrary length, which first column is gender (binary 0 or 1 for male o female), the second is age, the third is wage. How can I split this matrix into two submatrixes by gender using "for" and "if" functions? After that, i have to plot the wage versus the age, using plus sign (+) as a marker style for women and a circle (O) for men.
Anybody can give me an answer? I suppose that are few lines of code.
For the first part I've tried this:
for i=1:11
if ex3(i,1)==0
A=ex3(i,:)
else
B=ex3(i,:)
end
end
but this doesn't return me 2 matrixes, but a series of vectors.
  댓글 수: 2
Iain
Iain 2014년 10월 2일
Is there a reason you're restricting yourself to if and for?
Gino Franco
Gino Franco 2014년 10월 2일
For learning reasons imposed by our teacher

댓글을 달려면 로그인하십시오.

채택된 답변

Mohammad Abouali
Mohammad Abouali 2014년 10월 2일
편집: Mohammad Abouali 2014년 10월 2일
If this is MATLAB programming class tell your teacher that using "for" and "if" is not necessary the correct way of learning matlab. Matlab has its own style of coding it's better to think that way. If it is a general programming class then the story is different.
So first the bad style MATLAB programming
female_ex3=[];
male_ex3=[];
for i=1:size(ex3,1)
if (ex3(i,1))==0)
male_ex3=[male_ex3;ex3(i,2:end)]; % Stripping of first column which tell you gender
else
female_ex3=[female_ex3;ex3(i,2:end)];
end
end
now a more accepted style in MATLAB
male_ex3=ex3( ex3(:,1)==0 , 2:end );
female_ex3=ex3( ex3(:,1)==1 , 2:end );
NOTE that I assumed 0 means male and 1 means female.

추가 답변 (1개)

Iain
Iain 2014년 10월 2일
This is the "simple" answer:
male = ex3(find(ex3(:,1) == 1),:);
female = ex3(find(ex3(:,1) == 0),:);
  댓글 수: 1
Mohammad Abouali
Mohammad Abouali 2014년 10월 7일
편집: Mohammad Abouali 2014년 10월 7일
You don't even need find . Look at the two last line of code in my answer.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by