Split array into sub arrays
조회 수: 5 (최근 30일)
이전 댓글 표시
Hi,
I am trying to split some data in x,y,z:
x = [351;333;337;341;346;350;354;359;363;368;372;377];
y = [145;180;182;184;186;188;190;192;194;195;197;198];
z = [31;31;30;28;28;26;24;23;21;20;19;18];
based on the values of another array named data:
data = [0,0,0,2,0,0,1,0,0,0,0,0];
So that when data = 2, the following values of x, y and z are calculated until data = 1. So in this case the data would be split into the following:
When data hits equal to 2:
x = [351;333;337;341];
y = [145;180;182;184];
z = [31;31;30;28];
And then up until data = 1:
x = [346;350;354];
y = [186;188;190];
z = [28;26;24];
and finally the after 1..
x = [359;363;368;372;377];
y = [192;194;195;197;198];
z = [23;21;20;19;18];
However I am really struggling getting this to work, it either extrapolates x, y and z when data is equal to 2 or brings up errors. Any help would be appreciated.
Cheers
댓글 수: 2
Jos (10584)
2017년 12월 14일
What do you want to with the subarrays? Store them, use them for input to a function?
채택된 답변
KL
2017년 12월 14일
편집: KL
2017년 12월 14일
Or use mat2cell,
res = mat2cell([x y z].',3,diff([0 find(data) numel(data)]))
you get the result in a cell array, each cell containing the data split you want
>> res{1}
351 333 337 341
145 180 182 184
31 31 30 28
>> res{2}
346 350 354
186 188 190
28 26 24
>> res{3}
359 363 368 372 377
192 194 195 197 198
23 21 20 19 18
댓글 수: 0
추가 답변 (1개)
Jos (10584)
2017년 12월 14일
This splits the x,y, and z values into separate blocks:
x = [351;333;337;341;346;350;354;359;363;368;372;377];
y = [145;180;182;184;186;188;190;192;194;195;197;198];
z = [31;31;30;28;28;26;24;23;21;20;19;18];
data = [0,0,0,2,0,0,1,0,0,0,0,0];
p = cumsum([0 data(1:end-1)]~=0) + 1 ;
c = arrayfun(@(k) struct('x', x(p==k), 'y', y(p==k), 'z', z(p==k)), 1:p(end), 'un', 0) ;
s = cat(1,c{:})
The structure s holds the three blocks of (x,y,z) as specified by data. For instance, s(1).x holds the x values from the beginning up to the first non-zero in data.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Types에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!