Filter löschen
Filter löschen

Cody Problem 19. Swap the first and last columns

1 Ansicht (letzte 30 Tage)
Hidd_1
Hidd_1 am 31 Mär. 2021
Beantwortet: Abhinav am 26 Apr. 2023
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 :)

Akzeptierte Antwort

John D'Errico
John D'Errico am 31 Mär. 2021
Bearbeitet: John D'Errico am 31 Mär. 2021
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.

Weitere Antworten (1)

Abhinav
Abhinav am 26 Apr. 2023
function B = swap_ends(A)
B = A;
k = B(:,1);
B(:,1) = B(:,end);
B(:,end) = k;
end

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by