Clear Filters
Clear Filters

take second element of cell

9 views (last 30 days)
skysky2000
skysky2000 on 25 Dec 2016
Commented: Image Analyst on 25 Dec 2016
Dear all, I have 500 cell this is part of it, a={[1,5] [2,36,74,56,73,5] [3,79,73,5] [4,74,56,73,5] [5] [6,12,5] [7,3,79,73,5] [8,25,97,69,61,3,79,73,5]}; I just want to take the second element from each cell and put it in spreat it array like:
b=[5 36 79 74 0 12 3 25];
Thanks...

Accepted Answer

the cyclist
the cyclist on 25 Dec 2016
Edited: the cyclist on 25 Dec 2016
Here's one way. I needed to make the temporary variable to accommodate the way you are handling the cell array element whose vector is length 1.
tmp = cellfun(@(x)[x 0],a,'UniformOutput',false);
b = cellfun(@(x)x(2),tmp)
clear tmp
  2 Comments
skysky2000
skysky2000 on 25 Dec 2016
Edited: Image Analyst on 25 Dec 2016
That's amazing.... Thanks a lot mate!
Image Analyst
Image Analyst on 25 Dec 2016
Amazing yes. For anyone finding it a bit cryptic, here's a explicit, brute force method using a for loop -- maybe not as efficient for long arrays, or MATLAB-ish, but possibly more intuitive and understandable for some readers:
a={[1,5] [2,36,74,56,73,5] [3,79,73,5] [4,74,56,73,5] [5] [6,12,5] [7,3,79,73,5] [8,25,97,69,61,3,79,73,5]}
for k = 1 : length(a)
thisCellContents = a{k};
if length(thisCellContents) > 1
% Normal case
b(k) = thisCellContents(2);
else
% Only one element in the vector so assign it 0
b(k) = 0;
end
end

Sign in to comment.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!