Create columns with no zero sequentially elements of a vector

1 view (last 30 days)
I have a vector A=[4,2 3 2 2 0 0 1 2 2 0 0 1 2 3] and I am trying to create columns in new matrix with no zero sequentially elements, with a loop without success.Β1=[4,2 3 2 2] B2=[1 2 2] etc
I want to have a column with elements of A and when I find zero to create another column. Do you believe that it is feasible?
  1 Comment
John D'Errico
John D'Errico on 28 Apr 2015
You do realize that matrices MUST be rectangular? So all columns of a matrix must be the same length. This is why you failed to produce a result, since your result would not have that property.

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 27 Apr 2015
Edited: Image Analyst on 27 Apr 2015
This is very easy with the Image Processing Toolbox. Simply use bwlabel() (and regionprops() if you're going to have some unknown number of regions rather than exactly 3).
A=[4 2 3 2 2 0 0 1 2 2 0 0 1 2 3]
labeled = bwlabel(A)
B1 = A(labeled==1)
B2 = A(labeled==2)
B3 = A(labeled==3)
Do you have that toolbox?
  9 Comments
Image Analyst
Image Analyst on 28 Apr 2015
For regionprops() to get the values of the original array, you need to supply it.
A=[4 2 3 2 2 0 0 1 2 2 0 0 1 2 3];
[labeled, numRegions] = bwlabel(A);
measurements = regionprops(labeled, A, 'PixelValues');
for k = 1 : numRegions
B{k} = measurements(k).PixelValues
end
See my Image Segmentation Tutorial for a more comprehensive and well commmented demo. http://www.mathworks.com/matlabcentral/fileexchange/25157-image-segmentation-tutorial
nmartz
nmartz on 28 Apr 2015
OK we did it, for one more time Image Analyst you are amazing!! Thanks a lot!!

Sign in to comment.

More Answers (1)

Andrei Bobrov
Andrei Bobrov on 27 Apr 2015
Edited: Andrei Bobrov on 27 Apr 2015
B = zeros(size(A));
t = A > 0;
B(strfind(0,t],[0,1])) = 1;
b0 = cumsum(B);
Bout = accumarray(b0(t)',A(t)',[],@(x){x'});
  1 Comment
nmartz
nmartz on 27 Apr 2015
Thanks for your response, I checked this but I had this output: Error using horzcat Dimensions of matrices being concatenated are not consistent.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!