0
votes

I have a 10 X 10 matrix, A, created in MatLab. All the values in the matrix are between 0 and 100. Say that I want to:

  1. Replace all elements of A < 10 with zeros
  2. Replace all elemtns of A > 90 with infinity
  3. Extract all values between 30 and 50 to a new vector.

Can I do this without writing a script? I can easliy do this through a script with some simple for-loops, but are there any shortcuts available? Any help will be greatly appreciated!

2

2 Answers

4
votes

All of these things are really easy to do using logical indexing:

Each of the operations above can be done quite easily using a one or two commands. However each operation must be done independent of the other two. You can't do all 3 in one line.

1.

smallIdx = A<10;
A(smallIdx) = 0;
% One Line Version
A(A<10) = 0; 

2.

bigIdx = A>90;
A(bigIdx)=inf;
% One Line Version
A(A>90) = inf;

3.

middleIdx = A>30 & A<50;
newVector = A(middleIdx); 
% One Line Version
newVector = A(A>30 & A<50);

new vector is a vector and wont be square like A was

0
votes

Set up any 3 × 3 matrix a. Write some command-line statements to perform the following operations on a: (a) interchange columns 2 and 3; (b) add a fourth column (of 0s); (c) insert a row of 1s as the new second row of a (i.e., move the current second and third rows down); (d) remove the second column.