How to convert cell to numeric
조회 수: 10 (최근 30일)
이전 댓글 표시
I have used "readtable" in order to import the same column from several excel. The type of data is "1P", "2P"...."6P". Once MATLAB has imported them, I use table2array to convert the table into an array. After this operation, I'd like to convert the values of each cell into numeric, I mean, convert the cell with 1P into 1, 2P into 2... 6P into 6. I have tried it by using "cell2mat" and then "str2num" but it doesn't work. Anyone can help me?
Thanks in advance.
for i=1:12
energia_activa(:,i)=readmatrix(meses(i),'Range','C2:C2999');
energia_reactiva(:,i)=readmatrix(meses(i),'Range','D2:D2999');
periodo(:,i)=readtable(meses(i),'Range','F2:F2999');
end
potencia_consumida=energia_activa.*4;
%Periodos
periodo_numcar=table2array(periodo);
periodo_num=zeros(2997,12);
for i=1:12
periodo_num=cell2mat(periodo_numcar(:,i));
end
댓글 수: 1
Rik
2020년 12월 10일
It is not quite clear to me what your data actually is, but why do you expect cell2mat to know what you want? You should write a parsing function that will convert your input char array to a value. Then you can either use a loop or cellfun to process the entire array.
(and don't use str2num, use str2double instead)
답변 (1개)
Arjun
2024년 9월 5일
I understand that you want to convert data which is currently in string format(“1P”) into numeric format(1).
To convert values like “1P”, “2P”, “3P” to numeric 1,2,3 in MATLAB, you can use the string manipulation functions. Since “cell2mat” and “str2num” aren't directly applicable here due to the presence of the letter "P", you can use “str2double” in combination with “erase” to remove the "P" and then convert the string to a number.
Kindly have a look at the modified code:
for i = 1:12
energia_activa(:, i) = readmatrix(meses(i), 'Range', 'C2:C2999');
energia_reactiva(:, i) = readmatrix(meses(i), 'Range', 'D2:D2999');
periodo(:, i) = readtable(meses(i), 'Range', 'F2:F2999');
end
potencia_consumida = energia_activa .* 4;
% Convert periodos to numeric values
periodo_numcar = table2array(periodo);
periodo_num = zeros(2997, 12);
for i = 1:12
% Remove the 'P' character and convert to double
periodo_num(:, i) = str2double(erase(periodo_numcar(:, i), 'P'));
end
Explanation:
- erase(periodo_numcar(:, i), 'P'): This function removes the "P" character from each string in the column.
- str2double(...): Converts the resulting strings (e.g., "1", "2", etc.) to numeric values.
To learn more about the above functions, kindly refer to the following documentation links.
“str2double”: https://www.mathworks.com/help/releases/R2020a/matlab/ref/str2double.html?searchHighlight=str2double&s_tid=doc_srchtitle
I hope this helps!
댓글 수: 0
참고 항목
카테고리
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!