Generate a cell with 10 elements
Afficher commentaires plus anciens
Hello,
I have the following assignment:
1.3 Generate a cell with ten elements. Each element is a vector of random length (between 1 and 10) containing ones if the length is odd and zeros if the length is even.
For which I've been given the following solution:
NumofVec = 10;
for 1 = 1:NumofVec;
Vlen = floor(rand*10)+1;
V{i} = ones (1, Vlen)*rem(Vlen,2);
end
Could you please explain to me the meaning of the last two lines?
Vlen = floor(rand*10)+1;
V{i} = ones (1, Vlen)*rem(Vlen,2);
Thanks a lot!
Massive thanks to anyone attempting to help!!
Silvi
1 commentaire
What exactly is your question? Do we need to explain the "=" operator also? Did you read the Getting Started chapters already, such that you are familiar with the cell indexing by the curly braces? Could we post anything better than the help sections for floor, rand, ones and rem?
You for loop contains a typo.
Réponse acceptée
Plus de réponses (2)
Andrei Bobrov
le 25 Oct 2014
Modifié(e) : Andrei Bobrov
le 25 Oct 2014
1 commentaire
Silviya
le 25 Oct 2014
Image Analyst
le 25 Oct 2014
Modifié(e) : Image Analyst
le 25 Oct 2014
I think Mohammad explained it pretty well. Here is the same code in a somewhat easier-to-understand style.
numberOfCells = 10;
V = cell(numberOfCells, 1);
for row = 1: numberOfCells
% Get a random number between 1 and 10 inclusive.
vectorLength = randi(10, 1)
% See if the length is odd or oven.
if rem(vectorLength,2) == 0 % Remainder is 0 so must be even.
% The length is an even number.
% Set V equal to a vector of all zeros.
V{row} = zeros(1, vectorLength);
else
% The length is an odd number.
% Set V equal to a vector of all ones.
V{row} = ones (1, vectorLength);
end
end
See the FAQ for a good intuitive understanding of how cell arrays work: http://matlab.wikia.com/wiki/FAQ#What_is_a_cell_array.3F
1 commentaire
Silviya
le 25 Oct 2014
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!