Extract only numbers from a cell array.
16 次查看(过去 30 天)
显示 更早的评论
Hi,
I have to use the Ybus from the output of OpenDSS in which the admittance is in the format of "21.30045+j-37.934". That too divided into 2 cells in a csv file. In matlab after using the [num_data text_data]=xlsread('filename'); I've got the imaginary entries in cell arrays. I need to extract the numbers only. For example, "-37.934" from the given entry. I've tried "regexp(text,'\d*','match');" but it only takes the numeric entries only, not the negative signs of decimal points. Then using "C=regexp(text,'+j','match');" I got another cell array containting all "+j" only. How can I compare the cells in "text" and "C" arrays and extract only the numbers with their signs excluding "+j"?
Thank you.
2 个评论
回答(2 个)
Adam Danz
2019-2-7
编辑:Adam Danz
2019-2-7
Here's a solution that first converts all elements that do not have a 'j' and then converts all elements that do have a 'j'.
% Fake data
t = {'21.30045+j-37.934', '200000', '21.30045+j-37.934', '1000000'};
% Convert
hasJ = contains(t, 'j'); %index of all elements that contain a 'j'
jIdx = regexp(t, 'j'); %index of each string where 'j' occurs
n = nan(size(t)); %allocate output
n(~hasJ) = cellfun(@str2num, t(~hasJ)); %convert elements that do not have a j
% now convert all elements that do have a 'j' but ignore everything before the j.
n(hasJ) = cellfun(@(x,y) str2num(x(y+1:end)), t(hasJ), jIdx(hasJ));
The result ('n') is a vector of class 'double' that is the same size as the input ('t').
n =
-37.934 2e+05 -37.934 1e+06
Luna
2019-2-7
Your data seems much more complicated than that and has commas inside cells as a char also.
I have removed white spaces, +j s, and commas inside cells between the numbers as a char. I put a space instead of commas then convert it to double.
So that you will get 265x531 double array all numbers.
Here you go:
[num,txt,raw] = xlsread('ieee123_EXP_Y.CSV');
dataCell = cell2mat(cellfun(@(x)str2num(x),cellfun(@(x) strrep(x,',',' '), cellfun(@(x) strrep(x,'+j',''),cellfun(@(x) strrep(x,' ',''),txt,'UniformOutput',false),'UniformOutput',false),'UniformOutput',false),'UniformOutput',false));
2 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!