How to recognise "blocks" in array in Matlab

조회 수: 2 (최근 30일)
Maheen Siddiqui
Maheen Siddiqui 2016년 5월 4일
답변: Bhavesh 2016년 5월 9일
I have an array in Matlab
A = [1 2 3 4 5 6 7 8 9;
67 67 67 86 86 86 86 67 67]';
where every point in the first row of A corresponds to a "code" either 67 or 86. I am trying to extract these blocks of "67s" and "86s" such that every time a block starts the corresponding elements are put into the 3rd dimension of a different array called X, where the .
So for e.g. in A I have 3 different blocks, so I would like to end up with an array X of size 1x9x3. And for e.g. the first 67 block I would like to have X
X(1,:,1) = [1 2 3];
I understand that I would "fill up" this vector X using a for loop
for i=1:size(A,2)
for j=1:size(A,2) %actually j should be up till the number of blocks present
X(1,i,j) = A(1,i)
end
end
But this isn't correct or complete of course because firstly I'm unsure how to separate out the "blocks" and how to correctly "fill in" the j's in X(1,i,j). Secondly how can I get the code to recognise how many blocks there are?
Can anyone help?
Thanks

답변 (1개)

Bhavesh
Bhavesh 2016년 5월 9일
A = [1 2 3 4 5 6 7 8 9; 67 67 67 86 86 86 86 67 67]'
temp = A(1,2);
lenA = length(A);
j = 1; k = 1;
for i=1:lenA
if temp == A(i,2)
X(1,j,k) = A(i,2);
temp = A(i,2);
j = j+1;
else
j = 1;
k = k+1;
X(1,j,k) = A(i,2);
temp = A(i,2);
j = j+1;
end
end

카테고리

Help CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by