0

I have read some data from an Excel file in Matlab. A cell array has been generated as follow:

x={'11', 'NaN', 'NaN', '13', 24}

I want to convert cell array to a numeric matrix (for other required calculations) and convert 'NaN' elements to zero in my numeric matrix. How can I do it?

Thank you.

2 Answers 2

2

You can use str2double to convert strings to numeric values:

x={'11', 'NaN', 'NaN', '13', '24'};
nx = str2double(x);

Once you have numeric values, you can substitute the nans with zeros:

nx(isnan(nx))=0
Sign up to request clarification or add additional context in comments.

1 Comment

@Yaser, this won't work if the input is as in the question - the last value (24) is a number, not a string. See my answer to deal with that.
0

In the example you gave in the question there is a mixed content (strings and numbers), so it takes 2 steps:

x = {'11', 'NaN', 'NaN', '13', 24}; % last value is a number
isch = cellfun(@isstr,x); % find all strings
numx(isch) = str2double(x(isch)); % convert the strings to numbers, and place the correcly
numx(~isch) = cell2mat(x(~isch)); % extract the numbers and place the correcly

Then you can replace all NaNs with zeros:

numx(isnan(numx)) = 0;

the result:

numx =

    11     0     0    13    24

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.