Splitting arrays based on row number resulting from for loop

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

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

Comment posted as answer by Ellen:
Thank you so much!
However, now I would like to use this for cell arrays. So the rows that needs to be split are stored in a cell array. I used it as follows:
splits{ii} = RowsToBeSplit;
if ~isempty(splits{ii})
splits{ii}=[splits{1}-1;diff(splits{ii}(:));size(A,1)-(splits{ii}(end)-1)];
else
splits{ii}=size(A,1);
end
output=mat2cell(A,splits{ii},size(A,2))
However now I get the following error:
Error using mat2cell (line 89)
Input arguments, D1 through D2, must sum to each dimension of the input matrix size, [32 3].
Error in Split_arrays (line 26)
output=mat2cell(A,splits{ii},size(A,2))
Obviously I am doing something wrong but I can't figure out what exactly. Can anyone help me?
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
Thank you so much! I have solved the problem now!

Sign in to comment.

More Answers (0)

Categories

Asked:

on 27 May 2020

Commented:

on 28 May 2020

Community Treasure Hunt

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

Start Hunting!