create a function that takes a vector as an input parameter and returns another vector where each component is the initial vector repeated n times.
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Nathali Londoño Torres
am 21 Mär. 2019
Kommentiert: Guillaume
am 24 Mär. 2019
create a function that takes a vector as an input parameter and returns another vector where each component is the initial vector repeated n times.
I have thought about doing the following:
function B = cyclic_shift_recursion(A,n) %n is the number of times the vector is repeated and A is the vector that I want to repeat
if n<=0
return
else
B=[A cyclic_shift_recursion(A,n-1)];
end
end
I get an error and I do not understand why, how can I correct this? Is there another easy way to do this? Thank you.
0 Kommentare
Akzeptierte Antwort
Guillaume
am 21 Mär. 2019
Bearbeitet: Guillaume
am 21 Mär. 2019
"Output argument "B" (and maybe others) not assigned during call to "cyclic_shift_recursion"
Well, yes matlab is correct. Your code:
function B = cyclic_shift_recursion(A,n) %n is the number of times the vector is repeated and A is the vector that I want to repeat
if n<=0
return
%... rest doesn't matter
So for n = 0, the function returns immediately, without assigning anything to B.
Simply assign something to B before returning. As it's homework, I'm not going to tell you what to assign, but it's very trivial.
As to your question:
" But how can I do a function that does this without using repmat"
There's all sort of ways you could cheat, avoiding repmat while not adhering to the spirit of your assignment (which it seems is to use recursion). E.g.:
kron(ones(1, n), A)
reshape(repelem(A(:),1, n), 1, [])
A(reshape((1:numel(A))' + zeros(1, n), 1, []))
and probably more...
6 Kommentare
Guillaume
am 24 Mär. 2019
Maybe, I misunderstood the assignment, but I would think that
cyclic_shift_recursion([1 2 3], 1)
should return [1 2 3], not [1 2 3 1 2 3]. That's the way repmat works.
Weitere Antworten (1)
Geoff Hayes
am 21 Mär. 2019
Nathali - what is the error message? What is cyclic_shift_recursion? Consider using repmat since your homework is indicating that you need to repeat each component in the initial array n times...
Siehe auch
Kategorien
Mehr zu Data Type Identification finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!