Cody Problem 19. Swap the first and last columns

7 ビュー (過去 30 日間)
Hidd_1
Hidd_1 2021 年 3 月 31 日
回答済み: Abhinav 2023 年 4 月 26 日
Hey I found problem with the Test 4 from the Cody Problem 19: Swap the first and last columns
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 :)

採用された回答

John D'Errico
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)
C = 1
D = A(:,1)
D = 1
Ok, so both C and D are created.
A(:,end) = [];
A(:,1) = [];
Matrix index is out of range for deletion.
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.

その他の回答 (1 件)

Abhinav
Abhinav 2023 年 4 月 26 日
function B = swap_ends(A)
B = A;
k = B(:,1);
B(:,1) = B(:,end);
B(:,end) = k;
end

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by