function [ newMatrixA, newMatrixB ] = SwapLastColumns( matrixA, matrixB )
% SwapLastColumns: Exchange the last columns of input matrices
% matrixA and matrixB and return new matrices.
% Inputs: matrixA, matrixB - input matrices, must have same
% number of rows so columns can be swapped
%
% Outputs: newMatrixA, newMatrixB - returned new matrices created
% from input matrices with last
% columns swapped
% Assign tempColumn with last column matrixA
tempColumn = matrixA(:, end); % FIXME
% Assign newMatrixA with first columns of matrixA and last
% column of matrixB
newMatrixA = [matrixA(:,end-1), matrixB(:,end)]; % FIXME
% Assign newMatrixB with first columns of matrixB and last
% column of matrixA
newMatrixB = [matrixB(:,end-1), matrixA(:,end)]; % FIXME
end
As you can see above, I've written code that I thought would correctly swap the last columns between the two matrices, but it gives me an error. For my test cases, when swapping a 3x2 and a 3x2 matrix, the code works. But, when swapping a 3x3 and a 3x2 matrix it won't work, and outputs a 3x2 answer instead of a 3x3. Not quite sure what I'm doing wrong. Any help is appreciated.

 채택된 답변

James Tursa
James Tursa 2020년 3월 31일

1 개 추천

From your description, I don't see how your code works for anything other that inputs having two columns. I would guess that this
newMatrixA = [matrixA(:,end-1), matrixB(:,end)]; % FIXME
newMatrixB = [matrixB(:,end-1), matrixA(:,end)]; % FIXME
should be this to include all of the beginning columns
newMatrixA = [matrixA(:,1:end-1), matrixB(:,end)];
newMatrixB = [matrixB(:,1:end-1), matrixA(:,end)];

댓글 수: 2

Kiernan King
Kiernan King 2020년 3월 31일
That worked! Thanks so much
Dyuman Joshi
Dyuman Joshi 2024년 3월 28일
Accepted as James's answer solves the problem posted.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

질문:

2020년 3월 31일

댓글:

2024년 3월 28일

Community Treasure Hunt

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

Start Hunting!

Translated by