Splitting arrays based on row number resulting from for loop

조회 수: 5 (최근 30일)
Ellen
Ellen 2020년 5월 27일
댓글: Ellen 2020년 5월 28일
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
Ellen
Ellen 2020년 5월 28일
Thank you so much! I have solved the problem now!

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

추가 답변 (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