dividing a column matrix based on the no

i have a single column matrix A=0 0 0 1 1 1 1 0 0 0 0 2 2 2 2 0 0 0 0 now i have to divide this in to several matrices such whenever 0 changes to 1 or 2 i want a new matrix in this case A1= 1 1 1 1 0 0 0 0; A2=2 2 2 2 0 0 0 0 which are also single column matrices

 採用された回答

Oleg Komarov
Oleg Komarov 2011 年 5 月 16 日

0 投票

A = [0 0 0 1 1 1 1 0 0 0 0 2 2 2 2 0 0 0 0].';
Split sequence (transforming in string)
out = regexp(sprintf('%d',A) ,'(1+0+|2+0+)','match');
Convert to double and store in cell array
c = cellfun(@(x) x.'-'0',out,'un',0)
c{1} % to retrieve the value
Organize eventually in structure with dynamic fields A001, A002, ..., An
numC = numel(c);
s = cell2struct(c, reshape(sprintf('A%03d', 1:numC),4,[]).',numC);
s.A001 % to retrieve the value
EDITED
With a loop
A = [0 0 0 1 1 1 1 0 0 0 0 2 2 2 2 0 0 0 0].';
c = 0;
s = 0;
% Start condition
if ismembc(A(1,1),1:2)
s = 1;
end
for n = 2:numel(A(:,1))-1
if A(n,1) == 0 && ismembc(A(n+1,1),1:2)
if s
c = c+1;
Out{c} = A(s:n,:);
end
s = n+1;
end
end
% End condition
if s < n
Out{c+1} = A(s:end,:);
end

7 件のコメント

bilhan
bilhan 2011 年 5 月 16 日
i am getting
cellfun(@(x) x.'-'0',out,'un',0)
ans =
[8x1 double] [8x1 double]
how could i retrieve those arrays
please send me a code using for loop
Oleg Komarov
Oleg Komarov 2011 年 5 月 16 日
See edit and search the documentation on how to operate with cell arrays or dynamic field indexing in structures
bilhan
bilhan 2011 年 5 月 16 日
thanks for your answer
but i want this done using a for loop
Oleg Komarov
Oleg Komarov 2011 年 5 月 16 日
You should have stated it in the first request.
bilhan
bilhan 2011 年 5 月 16 日
thank you very much
bilhan
bilhan 2011 年 5 月 16 日
now ia m getting
c{1}=1111 insyead of 11110000
Oleg Komarov
Oleg Komarov 2011 年 5 月 16 日
Do you use the same A? If not post the input array/vector.

サインインしてコメントする。

その他の回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2011 年 5 月 16 日

0 投票

more variant
A = A(:);
I = cumsum([0;diff(A)]~=0 & (A ~= 0));
out = arrayfun(@(x)A(I==x),1:max(I),'un',0);
same with the loop
A = A(:).';
I = cumsum([0,diff(A)]~=0 & (A ~= 0));
out = cell(1,max(I));
for j = 1:max(I),
out{j} = A(j==I);
end

4 件のコメント

bilhan
bilhan 2011 年 5 月 16 日
thank you man thbats wonder ful perfect thats what i want.
bilhan
bilhan 2011 年 5 月 16 日
the same question but an extension if A is a two columned matrix and i want to divide it based on the first column same as above then
for eg:_
a=[0 0;0 1;1 1;1 0;0 1;0 0;0 1;2 0;2 1;0 0;0 1]
a1=[1 1;1 0;0 1;0 1]
a2=[2 0;2 1;0 0;0 1]
Oleg Komarov
Oleg Komarov 2011 年 5 月 16 日
I edited my solution to take into account initial conditions (if A doesn't start with a 0) and to split a matrix on the basis of the first array.
bilhan
bilhan 2011 年 5 月 17 日
thank you

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeData Type Identification についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by