MATLAB Answers

# Splitting an array in non equally length sub-arrays according to a flag value contained in another array

3 views (last 30 days)
Davide Almerico on 26 Apr 2021
Commented: Scott MacKenzie on 26 Apr 2021
Hi all, thanks for your help. I need some help in Matlab.
I need to split an array (called R1) of non fixed length according to another array (let's call it R2, same length as R1). R2 has almost all empty cells, but only in some cells there's a character which is a "flag" for splitting the R1. So when R2 has a flag, then split R1 in the same index and create a new array.
Could you please help me on this with a simple example (10 indexes for example).
Thank you very much for your help.
##### 1 CommentShowHide None
Scott MacKenzie on 26 Apr 2021
You are asking for a simple example of a solution in MATLAB. But, it would help if you give an example!
Give an example for R1 and R2 and the result you are seeking.
I'm asking because it's not clear (to me, anyway) what type of data are in R1. It seems R2 is a character or string array, right? What about R1?

Sign in to comment.

### Answers (1)

Jonas on 26 Apr 2021
Edited: Jonas on 26 Apr 2021
so if your flag specifies the end of the current R1 sub part then you could write something like
flaggedIdx= find(~cellfun('isempty',R2)); % get idx of non empty cells
if flaggedIdx(1)~=0
flaggedIdx=[0 flaggedIdx]; % add flag for first element if necessary
end
if flaggedIdx(end)~=numel(R1)
flaggedIdx=[flaggedIdx numel(R1)]; % add flag for last element if necessary
end
arrayParts=cell(1,numel(flaggedIdx)-1); % N flags results into N-1 parts
for flagNr=2:numel(flaggedIdx)
arrayParts{flagNr}=R1((flaggedIdx(flagNr-1)+1):flaggedIdx(flagNr));
end
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

R2018a

### Community Treasure Hunt

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

Start Hunting!