Splitting arrays based on row number resulting from for loop

5 次查看(过去 30 天)
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?

采纳的回答

Rik
Rik 2020-5-27
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 个评论
Rik
Rik 2020-5-28
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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by