1

In Matlab, I have a 2x3 matrix, A, like this one:

A = [1 2 3; 4 5 6];

This matrix is defined inside of a function which takes a parameter, T. There are two cases that I need to take care of:

  1. T < 10
  2. T >= 10

If the user entered, say, T=40, then the 2nd row of A should be selected to make the calculations. On the other hand, if say T=5, the first row of A should be selected.

I can write a simple if-else condition like this:

if (T<10)
    b = A(1,:) * ... %Do whatever with the first row
else
    b = A(2,:) * ... %Do whatever with the second row
end

However I was wondering if it's possible to play around with Matlab indexes to save myself the overhead of having to write this if-else condition all around my code (this condition has to be checked many times, in different parts of my program).

For example, I was hoping to reach a simple expression like A(T<10, :) which would work fine if T<10 but for T>=10 would return an empty matrix.

I've been racking my brains for some hours but I'm a bit of a novice in optimising Matlab scripts. Could anyone kick me in the right direction?

Jose Lopez Garcia
  • 972
  • 1
  • 9
  • 21
  • If your goal is just to reduce repetitive if-else blocks, you can first define a variable `rowSelector`. Then in the beginning of your function you can set `rowSelector` with only one if-else block and then do `A(rowSelectr,:)`. – jrook Apr 15 '17 at 19:26
  • Mmm, so true @jrook. Do you know if Matlab admits something like rowSelectr = T < 10? 1 : 2 like in C++? (I've tried and doesn't seem to work, I think I'll have to write a complete if-else at least one time for the rowSelectr variable) – Jose Lopez Garcia Apr 15 '17 at 19:30
  • I don't think so. You can use [this answer](http://stackoverflow.com/questions/27561881/one-liner-for-if-then) as a workaround. In any case a single if-else block on top of the function is nothing to worry about and it will be more efficient than any *clever* solution that would calculate the row every time you want to select a row. – jrook Apr 15 '17 at 19:32
  • I get it, thank you jrook for your time. – Jose Lopez Garcia Apr 15 '17 at 19:35

1 Answers1

3

You can use the following method:

A((T>=10) + 1, :)
m7913d
  • 10,244
  • 7
  • 28
  • 56