Please let me know a way to use for loop to extract the first row elements from each column of data and check a condition and store these in a matrix

5 views (last 30 days)
Consider a cell of strings containing gender and height information of some patients (but the data is a little bit messy). Gender is given as 'f','female','m' or 'male' and heights are given in feet or centimeter (some data point are missing). For example
{'f' 'm' 'f' 'female' 'male';
'5.9' '6' '172' '' '180' };
Write a function m=heightconvert(data) to convert the cell array data to a matrix of double m. Use 0 to represent female, 1 to represent male. And convert height into meters and represent any missing data points as NaN. Assume that any height value that is less than 10 is in feet and you need the convert those values to meters using 1 foot = 0.3048 meter. Use str2double() function to convert a string to a number.

Answers (1)

DGM
DGM on 26 Nov 2021
Something like this
C = {'f' 'm' 'f' 'female' 'male';
'5.9' '6' '172' '' '180' };
g = double(cellfun(@(x) x(1)=='m',C(1,:)));
h = cellfun(@str2double,C(2,:));
mask = h>=10;
h(mask) = h(mask)/100;
h(~mask) = h(~mask)*0.3048;
% show results
g
g = 1×5
0 1 0 0 1
h
h = 1×5
1.7983 1.8288 1.7200 NaN 1.8000
You'll still have to wrap this up as a function.

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!