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 Center および File ExchangeMultidimensional Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by