Convert the mxn size Matrix to square Matrix without using loop or if

13 views (last 30 days)
Hi,
I have a random mxn matrix, like 4x6 and I want it to be square. For example, a original 4x6 matrix would be created by deleting the first and second column to a formed a 4x4 matrix.
A =
0.8147 0.6324 0.9575 0.9572 0.4218 0.6557
0.9058 0.0975 0.9649 0.4854 0.9157 0.0357
0.1270 0.2785 0.1576 0.8003 0.7922 0.8491
0.9134 0.5469 0.9706 0.1419 0.9595 0.9340
B =
0.9575 0.9572 0.4218 0.6557
0.9649 0.4854 0.9157 0.0357
0.1576 0.8003 0.7922 0.8491
0.9706 0.1419 0.9595 0.9340
How can I create from A to B without using loop or if-statment? and it should be work for all mxn, which m and n could be any number.
I started like this but got stunned. [m n] = size(A);
newA(m,:) = [];
newA(:,n) = [];
Thanks

Accepted Answer

Geoff Hayes
Geoff Hayes on 11 Nov 2014
Edited: Geoff Hayes on 11 Nov 2014
David - if you want to convert your (say) 4x6 matrix into a 4x4 by removing the first two columns, then you could do something like
B = A(:,3:end);
In the above, we use the colon to mean "all rows", and the 3:end to mean "get columns 3 through to the end". You can extend this to other (different sized) matrices.
EDIT
In your code where you try to set the mth row to the empty matrix, and the nth column to the empty matrix
newA(m,:) = [];
newA(:,n) = [];
what you really want to do is to set the first two columns to be the empty matrix which has the effect of removing them. Try
newA = A;
newA(:,1:2) = [];
  3 Comments
Geoff Hayes
Geoff Hayes on 11 Nov 2014
If your matrix is an mxn, with n>m, then you can do
B = A(:,m-n+1:end);
And if m>n, then presumably you still want an nxn matrix but with n rows. So try
B = A(m-n+1:end,:);

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 11 Nov 2014
Try this:
clc;
A =[...
0.8147 0.6324 0.9575 0.9572 0.4218 0.6557
0.9058 0.0975 0.9649 0.4854 0.9157 0.0357
0.1270 0.2785 0.1576 0.8003 0.7922 0.8491
0.9134 0.5469 0.9706 0.1419 0.9595 0.9340]
[rows, columns] = size(A);
if rows > columns
% Delete rows. Take bottom-most rows
numRowsToDelete = rows - columns
newA = A(numRowsToDelete+1:end, :)
elseif rows < columns
% Delete columns
numColumnsToDelete = columns - rows
newA = A(:, numColumnsToDelete+1:end)
end

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!