# Math Help - Matlab function M-Files

1. ## Matlab function M-Files

hi, im new to this software and need some help for these following questions:

the 1st question is to define a user defined function randVector(d,n) which returns a vector of d rows filled with zeros, except for n randomly placed non-zero elements (any random value). this is what i've done:

function e=randVector(d,n)
r=rand(n,1);
e=zeros(d,1);
a=[r;zeros(d-n,1)];
s=randperm(d);
for i=1:d
e(i)=a(s(i));
end
end

im stuck with the 2nd one:
Use a conditional if statement and create vector M=randVector(j+2,k+1), for k<j and j, k are the first and the last element of x respectively. (x is a given vector of 6 digits )

thanks

2. Originally Posted by boredmonkey
hi, im new to this software and need some help for these following questions:

the 1st question is to define a user defined function randVector(d,n) which returns a vector of d rows filled with zeros, except for n randomly placed non-zero elements (any random value). this is what i've done:

function e=randVector(d,n)
r=rand(n,1);
e=zeros(d,1);
a=[r;zeros(d-n,1)];
s=randperm(d);
for i=1:d
e(i)=a(s(i));
end
end

im stuck with the 2nd one:
Use a conditional if statement and create vector M=randVector(j+2,k+1), for k<j and j, k are the first and the last element of x respectively. (x is a given vector of 6 digits )

thanks
Code:
j=x(1);k=x(length(x));
if k<j
M=randVector(j+2,k+1)
else
M=[]
end