Cody Problem 19. Swap the first and last columns
조회 수: 4 (최근 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에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!