Splitting arrays based on row number resulting from for loop

5 views (last 30 days)
Hi! so I got a for loop which gives me the values of the rows at which an array needs to be split. I used this for multiple arrays so the values of these resulting rows and also the number of splits differs per array. So for example, the for loop produces the values 3 and 8, indicating the array must be split at row 3 and row 8. But it can also give more values, indicating more splits are needed, or no values, indicating no splits are needed. The arrays also differ in size.
Does anyone know a command in which I can put the row numbers where the array needs to be split? I thought about mat2cell but I don't know how to use this with only the row numbers where it needs to be split.
Any tips?

Accepted Answer

Rik
Rik on 27 May 2020
Here you go:
data=(1:10)'+(0:1);%generate some data
splits=[3 8];%use the splits you mentioned
if ~isempty(splits)
splits=[splits(1)-1;diff(splits(:));size(data,1)-(splits(end)-1)];
else
splits=size(data,1);
end
output=mat2cell(data,splits,size(data,2))
  3 Comments
Rik
Rik on 28 May 2020
You need to make sure to unpack all the variables to the expected data types. If it helps you can even wrap it in a function. That way it is easier to see what should go in and what comes out:
function output=apply_split(data,splits)
%splits the array data on the rows in splits
%if splits is empty, output={data};
if ~isempty(splits)
splits=[splits(1)-1;diff(splits(:));size(data,1)-(splits(end)-1)];
else
splits=size(data,1);
end
output=mat2cell(data,splits,size(data,2))
end

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!