Convert cell of mixed real and complex numbers into double

Convert the following cell array into double,
dd=[ {[1.0000e-03]} {[ 0]}
{[ 0]} {'10.06+28.21i'}]

답변 (2개)

Stephen23
Stephen23 2023년 10월 9일
편집: Stephen23 2023년 10월 9일
Without evil STR2NUM:
C = {1.0000e-03,0;0,'10.06+28.21i'}
C = 2×2 cell array
{[1.0000e-03]} {[ 0]} {[ 0]} {'10.06+28.21i'}
M = str2double(C);
X = isnan(M);
M(X) = [C{X}]
M =
0.0010 + 0.0000i 0.0000 + 0.0000i 0.0000 + 0.0000i 10.0600 +28.2100i
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)
outputmat =
0.0010 + 0.0000i 0.0000 + 0.0000i 0.0000 + 0.0000i 10.0600 +28.2100i
%%%%%%%%%%%%%%%%%%%%%%%%%%
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

카테고리

도움말 센터File Exchange에서 Data Type Conversion에 대해 자세히 알아보기

제품

릴리스

R2022b

질문:

2023년 10월 9일

편집:

2023년 10월 9일

Community Treasure Hunt

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

Start Hunting!

Translated by