gather elements of a cell

4 次查看(过去 30 天)
kix
kix 2020-7-10
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

回答(1 个)

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

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by