Convert cell of mixed real and complex numbers into double
3 views (last 30 days)
Show older comments
Convert the following cell array into double,
dd=[ {[1.0000e-03]} {[ 0]}
{[ 0]} {'10.06+28.21i'}]
Answers (2)
Mathieu NOE
on 9 Oct 2023
hello
try this
don't remember where I found this code , probably in the Fex section. many thanks to his creator !
oh, yes, this is it :
I just changed the name of the function to avoid a conflict with the native cell2num function
dd=[ {[1.0000e-03]} {[ 0]}
{[ 0]} {'10.06+28.21i'}];
[outputmat]=another_cell2num(dd)
%%%%%%%%%%%%%%%%%%%%%%%%%%
function [outputmat]=another_cell2num(inputcell)
% Function to convert an all numeric cell array to a double precision array
% ********************************************
% Usage: outputmatrix=cell2num(inputcellarray)
% ********************************************
% Output matrix will have the same dimensions as the input cell array
% Non-numeric cell contest will become NaN outputs in outputmat
% This function only works for 1-2 dimensional cell arrays
if ~iscell(inputcell), error('Input cell array is not.'); end
outputmat=zeros(size(inputcell));
for c=1:size(inputcell,2)
for r=1:size(inputcell,1)
% original code
% if isnumeric(inputcell{r,c})
% outputmat(r,c)=inputcell{r,c};
% else
% outputmat(r,c)=NaN;
% end
%Works great if you use addition by C Schwalm to the if statement. If statement within the code should now look like :
if isnumeric(inputcell{r,c})
outputmat(r,c)=inputcell{r,c};
elseif isnumeric(str2num(char(inputcell{r,c}))) %addition
outputmat(r,c)=str2num(char(inputcell{r,c})); %addition
else
outputmat(r,c)=NaN;
end
end
end
end
0 Comments
See Also
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!