Stuart’s MATLAB Videos

Watch and Learn

MATLABdo: The Way of MATLAB

I work in technical support, so very often I get strange requests.

Really strange.

My first question is “Why do you want to do that?” The reason I ask this is very often new MATLAB users are fighting against the way that MATLAB wants to work. If Aikido is “the Way of harmonious spirit” (or “the Way of Water” as I learned it) then MATLABdo should be “the Way of MATLAB”. Once users understand the MATLAB way of doing things, they can often do a task in a better way and then the specific syntax question they had does not matter. In fact, their code often becomes simpler, shorter and easier to maintain.

What is The MATLAB Way?

It is really hard to say, but I know it when I see someone going against it.

Let’s look at an example of going against MATLAB and how to fix it.

This MATLAB user wanted to make a series of variables to store some scalars. For example:


a1 = 11;
a2 = 22;
a3 = 33;

This lead to the next problem, where they would want to refer to one of these variables, but would not know which until run time. They just knew they would want to use one with a value of i.

i = 3;

So, they would want the following when i is three:

answer = a3 + i;

But, they would want the following when i is one:

answer = a1 + i;

That is when they came to ask me how they could do this.

The answer would be:

answer = eval(['a' num2str(i) ' + ' num2str(i) ';']);

However, to answer this question would be a great disservice to this MATLAB user, because their code should look like this:


a = [11 22 33];
i = 3;
answer = a(i) + i;

Much cleaner, it utilizes the fact that MATLAB (MATrix LABratory) thinks of everything as a matrix.


Since it is hard to describe MATLABdo, can you help me relate experiences of following it, or not following it?
|
  • print

コメント

コメントを残すには、ここ をクリックして MathWorks アカウントにサインインするか新しい MathWorks アカウントを作成します。