Shifting an array without circshift
94 次查看(过去 30 天)
显示 更早的评论
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
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.
回答(2 个)
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])
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 个评论
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)
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!