% x is a vector given in main program
function y = userfunction2(x,k)
x=y;
for i=i:k
y=userfunction(y);
end

댓글 수: 5

Akira Agata
Akira Agata 2017년 11월 12일
I don't think this function works.
What is the purpose of the second line ('x=y;')? Why input variable x is replaced by y? What is y??
What is the userfunction(y) in the third line?
William Brannon
William Brannon 2017년 11월 12일
편집: Walter Roberson 2017년 11월 12일
function y = LeftShift(x)
% x is a row n-vector and y is a row n-vector that is the left shift of x.
n=length(x);
y=zeros(n,1);
for k=1:n
if k<n;
y(k)=x(k+1);
else
y(n)=x(1);
end
end
William Brannon
William Brannon 2017년 11월 12일
It is a fuction to shift a given vector. the first value in hte vector goes to the nth place, the other values shift 1 position to the right.
William Brannon
William Brannon 2017년 11월 12일
the original function works, but I am supposed to do it without a loop. LeftShift is okay with a loop,but the other one is supposed to shift it k times, which is entered by another user.
William Brannon
William Brannon 2017년 11월 12일
What I really want is afunction that does this without a loop "k" times:
ShiftLeft(...(ShiftLeft(y)...)

댓글을 달려면 로그인하십시오.

 채택된 답변

Walter Roberson
Walter Roberson 2017년 11월 12일

1 개 추천

See fold()

댓글 수: 2

William Brannon
William Brannon 2017년 11월 12일
I'm sorry, but I don't understand how this works. What would the code actually look like?
I was thinking of vector operations to complete it, but I am not that familiar with how to use it in this case.
ShiftLeftAux = @(V) {ShiftLeft(V)}
t = cell(1,k); t{1} = {y});
t2 = fold(ShiftLeftAux, t);
result = t2{1};
Not nearly as clean as I would like.
This does not really vectorize the loop, though: it merely hides the loop into fold(), the same as if you had just written a routine that did the operation multiple times.
If you want actual vectorization you should instead be using circshift().
There is no way in MATLAB to say "vectorize this arbitrary linear code": there are only ways to get it to apply the linear code without you writing a visible for loop. The results are typically slower than using a for loop.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Akira Agata
Akira Agata 2017년 11월 13일

0 개 추천

Seems that you would like to do circshift ?
Your 'y = ShiftLeft(x)' seems equivalent to 'y = circshift(x,1)', like:
x = 1:10;
y = circshift(x,1);
Then, y becomes
>> y
ans =
10 1 2 3 4 5 6 7 8 9
If you want to shift k times, you should simply do 'y = circshift(x,k)'. Please see more detail on circshift documentation page .

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2017년 11월 12일

답변:

2017년 11월 13일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by