Handling data cell array
이전 댓글 표시
Hi there,
I am working with a cell array (numbers and strings) and need to reorganise my data. The problem is I struggle to rearrrange the data from my cell array.
This is an example of what I have:
A = {'x 30%/y 20%' 'x 10%' 'x 50%/z 40%' 'z 15%' 'y 5%/z 90%' 'z 25%'}';
I would like to rearrange the data from the array A in three columns, corresponding to x, y and z where each row correponds to the number accompanying each string value (x,y, and z) and zero in case there is no explicit string value. Specifically, I would like to have something like this:
B = [30 20 0; 10 0 0; 50 0 40; 0 0 15; 0 5 90;0 0 25];
Thanks a lot in advance for any help/hint.
Best wishes,
Fco.
Ps: I'm using Matlab R2019b
채택된 답변
추가 답변 (1개)
Paul Hoffrichter
2021년 1월 30일
편집: Paul Hoffrichter
2021년 1월 30일
Yes, regex is elegant. Here is a non-regex script.
This algorithm allows the x,y,z to be in any order in each row of A.
A = {'x 30%/y 20%' 'x 10%' 'x 50%/z 40%' 'z 15%' 'y 5%/z 90%' 'z 25%'}'
Alen = length(A);
B = zeros(Alen,3);
letters = {'x', 'y', 'z'};
for row = 1:Alen
entry = A{row};
col = 1;
for ch = letters
lOffset = strfind( entry, ch );
if ~isempty( lOffset )
pOffset = find( entry(lOffset+1:end) == '%', 1, 'first' );
B(row,col) = str2double(entry( lOffset+1: lOffset+1+pOffset-2 ));
end
col = col + 1;
end
end
B
Output:
A =
6×1 cell array
{'x 30%/y 20%'}
{'x 10%' }
{'x 50%/z 40%'}
{'z 15%' }
{'y 5%/z 90%' }
{'z 25%' }
B =
30 20 0
10 0 0
50 0 40
0 0 15
0 5 90
0 0 25
카테고리
도움말 센터 및 File Exchange에서 Data Type Conversion에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!