Cody Problem 19. Swap the first and last columns
2 次查看(过去 30 天)
显示 更早的评论
here is my solution:
function B = swap_ends(A)
C = A(:,end);
D = A(:,1);
A(:,end) = [];
A(:,1) = [];
B = [C A D];
end
For A=1, I got an error and idn how should I solve that.
I would appreciate any help! Thanks in advance :)
0 个评论
采纳的回答
John D'Errico
2021-3-31
编辑:John D'Errico
2021-3-31
This is NOT a provblem with the Cody problem, but with your code to solve it.
First, see what happens when A is 1. I'll show what happens just using those commands, not inside a function, so you can look to understand what happens.
A = 1;
C = A(:,end)
D = A(:,1)
Ok, so both C and D are created.
A(:,end) = [];
A(:,1) = [];
Now you tried to delete the last column, then the first column. But once you deleted the last column, there was no longer ANY first column, so MATLAB throws an error.
Worse, even if that worked, creating an empty matrix A, then what would have happened?
B = [C A D];
So if A was a scalar at first, then even if what you did created an empty array, then B would now be an array of the wrong size, since it would now have TWO columns!
How would I have implemented this? VERY DIFFERENTLY! In one line, perhaps as:
A(:,[1 end]) = A(:,[end,1]);
There may be a more efficient way to solve it than that, but this seems the obvious solution. It would also gain a far better Cody score than what you did. Does it work? Try it.
>> A = 1
A =
1
>> A(:,[1 end]) = A(:,[end,1])
A =
1
>> A = magic(5)
A =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
>> A(:,[1 end]) = A(:,[end,1])
A =
15 24 1 8 17
16 5 7 14 23
22 6 13 20 4
3 12 19 21 10
9 18 25 2 11
When you think you found an error in the problem, first make sure it is not an error in the logic of your solution.
0 个评论
更多回答(1 个)
Abhinav
2023-4-26
function B = swap_ends(A)
B = A;
k = B(:,1);
B(:,1) = B(:,end);
B(:,end) = k;
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!