Creating an array from a matrix based on if statement outputs

15 views (last 30 days)
Hello, I am still pretty new to MATLAB and programming in genral and ws looking to get some help with a problem I cant seem to solve. I have a matrix with 2 columns and 180 rows where column 1 has logical vlaues (0 and 1) and column 2 has some measured distances. i would liketo sort the data in column 2 into 2 arrays based on what the logical value in column 1 is. Basically I would like to seperate 1 logical value measuments into 1 array and the 0 logical values into anothey array.
I currently have a for loop that runs though a for loop for the lenght of my matrix and the for loop had an if statment inside of it that checks the logical value in column 3 to see if it is equal to 1. if its a 1 then it displays MALE and if it is a 0 then it is displays FEMALE. The reason I use the disp is to show that it if statments and for loop is working correctly to "see" which id which. Id like to put some code in the if and else statement where if the row is a male it put the value in an array for male dataand if female it will put the value in an array for female data. The actual matric has more than 2 colums hence why in the code below you see 3, but I am only working with 2 column out of the several that are present. I have put the for loop nested with the if sttemanet I have below. Thank you for any help in advance!
for i = 1:length(NumbersOnlyData)
if NumbersOnlyData(i,3) == 1
disp('MALE');
else
disp('FEMALE');
end
end

Answers (1)

Cris LaPierre
Cris LaPierre on 22 Feb 2021
Edited: Cris LaPierre on 22 Feb 2021
As my opinion, based on what you have described, I would not use a for loop or an if statement. Doing so does not take advantage of the matrix capabilities of MATLAB.
I would use logical indexing to select either the male or female data. If I can do that successfully, there may be no need to create two separate arrays.
Look at Ch 5 and Ch 12 of MATLAB Onramp.
A = [randi(2,10,1)-1,rand(10,1)]
A = 10×2
1.0000 0.3131 1.0000 0.9270 1.0000 0.0112 0 0.9770 0 0.3333 1.0000 0.6496 0 0.8062 0 0.1704 0 0.0806 0 0.8757
male = A(:,1)==1;
% for males, mulitply value in column 2 by 3
A(male,3) = A(male,2)*3;
% for females (syntax is 'not male'), divide value in column 2 by 3
A(~male,3) = A(~male,2)/3
A = 10×3
1.0000 0.3131 0.9394 1.0000 0.9270 2.7810 1.0000 0.0112 0.0335 0 0.9770 0.3257 0 0.3333 0.1111 1.0000 0.6496 1.9488 0 0.8062 0.2687 0 0.1704 0.0568 0 0.0806 0.0269 0 0.8757 0.2919

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!