how to separate string matrix by zeros
조회 수: 1 (최근 30일)
이전 댓글 표시
I imported some tables into matlab as string matrices. Each row contains 16 values. I would like to separte them by a group of zeros but don't know how to do it. For example, as highlighted on the image
I'd like to extract those three sections from the matrix, but don't know how to code the loop
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/639470/image.png)
k=1;
for i=1:size(m,1)
x = m(i,:);
str = sprintf('%s,', x{:});
num = sscanf(str, '%g,', [16, inf]);
val(:,k)=num;
if sum(val(:,k))~=0
% read more rows in until sum(num)==0
k=k+1;
else
end
end
댓글 수: 1
채택된 답변
Stephen23
2021년 6월 2일
편집: Stephen23
2021년 6월 2일
This would have been easier if you had imported the data as numeric, rather than as string.
Rather than relying on low-level loops and inefficient array expansion the MATLAB approach would be to use indexing and handle the entire matrix or "non-zero blocks" at once. For example:
S = load('matlab.mat')
M = sscanf(sprintf('%s,',S.m),'%f,',[16,Inf]).' % convert to numeric
Your question is unclear what you expect for the output. If you want one numeric matrix with all "non-zero" rows in it, then just use basic MATLAB indexing:
X = any(M~=0,2);
Z = M(X,:)
If you want to keep those "non-zero groups" separate then you should split them into a cell array:
D = diff([false;X;false]);
Y = find(D<0)-find(D>0);
C = mat2cell(M(X,:),Y,16);
Checking the first three matrices:
C{1:3}
추가 답변 (1개)
KSSV
2021년 6월 2일
id = zeros([],1) ; % indices of required strings
count = 0;
for i = 1:size(m,1)
t = str2num(m(i,:)) ;
if any(t)
count = count+1 ;
id(count) = i ;
end
end
iwant = m(id,:)
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!