How to initialize a vector in MATLAB as per a pattern?
I am completely new to MATLAB.This may be a rather basic question.
Given numerical values for size
, extras
and max
, I need to initialize a 1 X N vector such that the first size
elements are 1, the next size
are 2, the next size
are 3 and so on till the last size
elements are set to max
. So I need to initialize size
number of elements successively to x
such that x
increments from 1 to max
. The extras are the number of leftover cells which are initialized to 0. To illustrate:
size = 3; %# (is sam开发者_运维问答e as the quotient of N/max)
extras = 1; %# (is same as remainder of N/max)
max = 3;
N = 10;
original_vector = [0 0 0 0 0 0 0 0 0 0];
The desired output is
Required_vector = [1 1 1 2 2 2 3 3 3 0]
Maybe something using the Kronecker product:
N = 10;
max = 3;
extras = rem(N, max);
size = floor(N/max);
v = [kron([1 : max], ones(1,size)) zeros(1, extras)];
I took a guess about how extras and size are calculated. You said size is N % max and extras is N rem max, but those are the same thing(?).
Some reshaping acrobatics should do it:
>> size = 3; >> max = 3; >> N = 10; >> v = zeros(1, N); >> v(1:size*max) = reshape(cumsum(ones(max, size))', size*max, 1) v = 1 1 1 2 2 2 3 3 3 0
Another example:
>> size = 4; >> max = 5; >> N = 23; >> v(1:size*max) = reshape(cumsum(ones(max, size))', size*max, 1) v = Columns 1 through 18 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 5 Columns 19 through 23 5 5 0 0 0
This is a quite dirty implementation, but as you say you are very new to MATLAB, it might be better for you to see how you can more or less brute force a solution out. The trick here is the index reference done on Vec to place the numbers in. I have ignored the parameter extras and instead fill the vector up as best can be with the elements
N = 23;
max = 3;
size = 4;
Vec = zeros(N,1);
for i=1:max
for j=1:size
Vec((i-1)*size +1 + (j-1)) = i;
end
end
Vec'
extra = sum(Vec==0)
Output: ans =
1 1 1 1 2 2 2 2 3 3 3 3 0 0 0 0 0 0 0 0 0 0 0
extra =
11
A slight modification of @b3's solution:
N = 10;
mx = 3;
sz = floor(N/mx);
v = zeros(1,N);
v(1:mx*sz) = repmat(1:mx,sz,1)
精彩评论