Shifting an array without circshift
94 views (last 30 days)
Show older comments
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 Comments
DGM
on 11 May 2023
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.
Answers (2)
Matt J
on 11 May 2023
Edited: Matt J
on 11 May 2023
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])
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.
0 Comments
John D'Errico
on 11 May 2023
Edited: John D'Errico
on 11 May 2023
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)
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)
circshift(A,1)
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)
circshift(A,-2)
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.
0 Comments
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!