gather elements of a cell

6 visualizzazioni (ultimi 30 giorni)
kix
kix il 10 Lug 2020
Risposto: Image Analyst il 10 Lug 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

Risposte (1)

Image Analyst
Image Analyst il 10 Lug 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]

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by