How do I add to a cell array based on logicals?

조회 수: 1 (최근 30일)
Mitch Hezel
Mitch Hezel 2021년 4월 22일
댓글: Mitch Hezel 2021년 4월 22일
I have two arrays, A and B.
A is an array of random numbers. B is an array of logicals, either 0 or 1. A is the same length as B.
For as long as B is 0, I want to add the data from A at those indices to a cell in a separate cell array.
for example,
A = [1 2 3 4 5 6 7 8 9 10]
B = [1 0 0 0 1 0 0 0 1 0].
The code should output C, where C{1} = [2,3,4], C{2} = [6 7 8], C{3} = 10. How should I accomplish that?
I'm currently doing it with a bunch of for loops which misses the last chunk of data, that is, it misses data in the event B doesn't end in 1.

채택된 답변

David Hill
David Hill 2021년 4월 22일
There might be an easier way. Here is one with a single loop.
b=num2str(B);
b=b(b~=' ');
[idx1,idx2]=regexp(b,'[0]+');
for k=1:length(idx1)
C{k}=A(idx1(k):idx2(k));
end
  댓글 수: 2
Mitch Hezel
Mitch Hezel 2021년 4월 22일
편집: Mitch Hezel 2021년 4월 22일
Looks like that actually works. The only change I had to make was changing b to be a row vector, since regexp is throwing an error if it isn't. Thanks dude! Edit: Ah, realizing that's probably my fault since I made it seem like my data was in row vectors with the example. Either way, it's working.
Mitch Hezel
Mitch Hezel 2021년 4월 22일
Interestingly, this code is cleaner than my code (by probably a factor of 3 or more) but it is much slower. Is regexp a slow operation?

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by