Shifting an array without circshift

93 次查看(过去 30 天)
HC98
HC98 2023-5-11
I want to shift an array and whilst circshift generally works, I encounter errors with certain configs. Is there a way to shift the array without using it?
  2 个评论
DGM
DGM 2023-5-11
It's hard to provide any answer unless you say how you're trying to use circshift() and what things you expect it to do that it doesn't do.
James Tursa
James Tursa 2023-5-12
Small examples always help people understand your question.

请先登录,再进行评论。

回答(2 个)

Matt J
Matt J 2023-5-11
编辑:Matt J 2023-5-11
circshift is not doing anymore than indexing into the array like below, so you could do that directly.
x=1:10;
xshift = x([end,1:end-1])
xshift = 1×10
10 1 2 3 4 5 6 7 8 9
However, as @DGM points out, there's no way to know what advice will avoid the errors you see, without knowing what you did to invoke them.

John D'Errico
John D'Errico 2023-5-11
编辑:John D'Errico 2023-5-11
Nobody can know what you did wrong. circshift DOES work. I'm not even sure what you would have done that would cause an error. The tool is pretty simple to use. By error, do you just mean you did not get what you wanted? But since we can't possibly know what you wanted, we cannot possibly help you. Would you ask your auto mechanic to diagnose what is wrong with your car, while not actually allowing the mechanic to touch or look at the car, and only saying that it does not work poperly?
The answer to that is NOT to then ask if someone teach you how to build your own car from scratch. It is far better to learn to use and understand the tools you have.
Can you circularly shift an array? Well, of course. That is trivial. Just use mod.
A = primes(20)
A = 1×8
2 3 5 7 11 13 17 19
I'll give an example of how it might work. Think about it, then look at the code.
nA = numel(A);
ind = 0:nA-1; % zero based index
A(mod(ind - 1,nA)+1) % The same as circshift(A,1)
ans = 1×8
19 2 3 5 7 11 13 17
circshift(A,1)
ans = 1×8
19 2 3 5 7 11 13 17
So, we can now see how one might build a simple function to circularly shift a vector.
mycircshift = @(A,shift) A(1 + mod((0:numel(A)-1) - shift,numel(A)));
mycircshift(A,-2)
ans = 1×8
5 7 11 13 17 19 2 3
circshift(A,-2)
ans = 1×8
5 7 11 13 17 19 2 3
The fact is though, you would be better off just using circshift. What I wrote is not any better. If has less functionality than circshift. And if using circshift gave you a problem, then I am sure you would have a problem debugging what you did wrong in the code I just wrote.
So unless you need a code to do something more than what circshift provides, then you should just learn to properly use circshift. And if you do need something more sophisticated, then you need to explain what circshift fails to do for you.

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by