Generate a cell with 10 elements
显示 更早的评论
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 个评论
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.
采纳的回答
更多回答(2 个)
Image Analyst
2014-10-25
编辑:Image Analyst
2014-10-25
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
类别
在 帮助中心 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!