how to use if else statement
6 次查看(过去 30 天)
显示 更早的评论
Hello,
I have a list of participants (A, B, C, D...) and would like to extract their data from the dataset X. This dataset has numerous missing data. As there are multiple rows for the same participant, I would like to
- to filter all the rows containing specified participant
- have an if else statement - if column 4 contains a 'Yes', to insert column 5 'Male' into an array Y. else if column 4 is 'No', to insert column 7 'Female' into the same array Y
- ideally, the output should look like a 4x2 array with each unique participant matched to their gender
A Male
B Male
C Female
D Female
I have attached the sample data here.
Thank you very much for your help.
采纳的回答
Clay Swackhamer
2023-8-2
Hope this helps. It uses an example built in dataset (carbig) to demonstrate some basics of working with data in tables. As with many things there is more than one way to solve this problem. Task 3 (reshaping the output) depends on your specific dataset but I think if you accomplish tasks 1 and 2 you will be able to solve it.
%% Load data
load carbig
% Put the data into a table
% First convert some variables to categorical
org = categorical(cellstr(org));
cyl4 = categorical(cellstr(cyl4));
cars = table(org,Model_Year,when,cyl4,Acceleration,Horsepower,Weight);
%% 1. Filter all rows containing specified participant
% Get all cars from Japan
japaneseCars = cars(cars.org == 'Japan',:)
%% 2. If/else statement
% If the car is a 4 stroke (YES) insert horsepower into an array called "output"
% If the car is is not a 4 stroke (NO) insert weight into the same array
% Go through the table one row at a time
for i = 1:height(japaneseCars)
if japaneseCars.cyl4(i) == 'Four' % YES case
output(i) = japaneseCars.Horsepower(i);
else % NO case
output(i) = japaneseCars.Weight(i);
end
end
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Descriptive Statistics and Visualization 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!