MATLAB Answers

gather elements of a cell

4 views (last 30 days)
kix
kix on 10 Jul 2020
Answered: Image Analyst on 10 Jul 2020
Hi everyone!
I have got a cell that is containing array and I would like to create a new array with the elements of this cell.
For example, I’ve got a cell like this one: A={[1 2 3] [4 5 6 7 8] [9 10]}
So if I want my new cell to have 5 elements, I would take the first three element of the in the 1st array and then I would pick randomly 2 elements in the second array to complete.
And my result would be like: B =[1 2 3 7 5]
Functions like cat and cell2mat would give me the 5 elements but I’m struggling with the random part.
Thanks in advance

  0 Comments

Sign in to comment.

Answers (1)

Image Analyst
Image Analyst on 10 Jul 2020
First of all, you do not have a cell that contains an array.
You have a cell array with 3 cells, each of which has a single row vector in it.
I think your confusion lies in not having read the FAQ on cell arrays, so please read it.
Anyway, here is code to do what you asked.
% Define the cell array A, which has 3 cells.
A={[1 2 3] [4 5 6 7 8] [9 10]}
% Get two random indexes in the second cell
randomIndexes = randperm(length(A{2}), 2)
% Get two elements from the contents of the vector in the second cell using randperm().
twoElements = A{2}(randomIndexes)
% Now concatenate them into a single row vector of class double.
B = [A{1}, twoElements]

  0 Comments

Sign in to comment.