Skip to Main Content Skip to Search
File Exchange
MATLAB Newsgroup
Link Exchange
  Blogs  
 Contest 
MathWorks.com

Loren on the Art of MATLAB

June 5th, 2007

Indexed Assignment

Recently some folks at The MathWorks wondered about the difference of behavior of variable creation versus assigning values into an existing array. I thought I'd address this topic live from The MathWorks Aerospace and Defense Conference '07.

Contents

Here's a picture of the audience.

The Question

Why doesn’t changing an element of a logical array change its logicalness? Most arithmetic operations remove the logicalness from an array; it would seem to me that changing an element of the array (at least to something other than 0 or 1) should either throw an error or similarly modify its logicalness.

An Example

Let's show an example. First create a logical array.

clear all
A = magic(3);
B = A > 6;
whos
  Name      Size            Bytes  Class      Attributes

  A         3x3                72  double               
  B         3x3                 9  logical              

Now let's do some arithmetic with logical arrays mixed with doubles.

C = B + 1;
D = B;
D(1:5) = 2
whos A B C D
D =
     1     1     0
     1     1     1
     1     1     0
  Name      Size            Bytes  Class      Attributes

  A         3x3                72  double               
  B         3x3                 9  logical              
  C         3x3                72  double               
  D         3x3                 9  logical              

What you see is that A and C are double arrays, while B and D are logical.

The Answer

Indexed assignment, that is, D(1:5) = 2 has always preserved the type of the array being indexed. Only values may change, not the type. You'd only get an error if there was not a valid conversion routine from the type on the right-hand side to the type stored on the left.

If you simply concatenate values, you also find that the output is logical:

E = [D ; B]
E =
     1     1     0
     1     1     1
     1     1     0
     1     0     0
     0     0     1
     0     1     0

To see this with another datatype, let's look at string array.

firstname = 'Loren'
lastname = [83   104   117   114   101]
name = firstname
name(end+2:end+1+length(lastname)) = lastname
firstname =
Loren
lastname =
    83   104   117   114   101
name =
Loren
name =
Loren Shure

If I just use straight concatenation, here's what happens

newname = [firstname, ' ', lastname]
newname =
Loren Shure

Arithmetic

If I perform arithmetic between mixed types, where one is numeric and one is not, I instead get a numeric answer.

name - 32
ans =
  Columns 1 through 8
    44    79    82    69    78   -32    51    72
  Columns 9 through 11
    85    82    69

Thoughts?

The fact that you get results with different datatypes depends on whether you are doing a numerical calculation or assigning to an array. Has the behavior been what you need or have you found it confusing? Let me know here.


Get the MATLAB code

Published with MATLAB® 7.4

12 Responses to “Indexed Assignment”

  1. Seth Popinchalk replied on :

    I remember this being very confusing back in R12 when double arrays, the full 64 bits, were tagged with a “logical” flag which would mean, zero is false and, non-zero was true. Very confusing. Thanks for this explanation!

  2. Kevin replied on :

    I just did the following experiments:

    >> clear
    >> x = logical([1 0 1 0 0])

    x =

    1 0 1 0 0

    >> whos
    Name Size Bytes Class Attributes

    x 1×5 5 logical

    >> x(1) = 2

    x =

    1 0 1 0 0

    >> whos
    Name Size Bytes Class Attributes

    x 1×5 5 logical

    I think Matlab should complain when I run x(1) = 2. Matlab does not do the operation I ask it to do and it does not complain. I think this is bad. Instead Matlab should generate error message and let the programmer to fix the problem.

  3. Wes Campaigne replied on :

    How does cat choose the ‘dominant’ class, i.e., the class of its return value?

    A quick experiment with the basic types seems to reveal a descending priority of:
    char
    integer types (if there are multiple different integer-typed operands, the type of the left-most of these is dominant)
    single
    double
    logical

    Appropriate warnings are given most of the time, but truncation of floats to char doesn’t throw any. And promotion of one integer type (or logicals) to a bigger integer type DOES throw a warning, even though it’s unnecessary.

    Is there a particular reasoning behind all this behaviour? I haven’t noticed it documented anywhere.

  4. Urs (us) Schwarz replied on :

    Any non-zero real element of input array X is converted to a logical 1 while zeros in X become logical 0.

    which makes a lot of sense, by the way…
    us

  5. Urs (us) Schwarz replied on :

    SNIP misunderstanding
    x=[false,true,false];
    x(1)=2;
    % x = 1 1 0
    I think Matlab should complain when I run x(1) = 2…

    not at all; the help clearly says:

    Any non-zero real element of input array X is converted to a logical 1 while zeros in X become logical 0.

    which makes a lot of sense, by the way…
    us
    sorry, first reply got screwed up

  6. Steve replied on :

    Wes,

    There’s a page in the MATLAB documentation that discusses concatenation of different data types:

    http://www.mathworks.com/access/helpdesk/help/techdoc/index.html?/access/helpdesk/help/techdoc/matlab_prog/f1-84864.html

    This is from the documentation for MATLAB 7.4 (R2007a) but I don’t believe this behavior has changed recently. The priority list you posted agrees with what’s in the documentation. This page also discusses the integer casting warning.

  7. Daniel Armyr replied on :

    I would have to join the group saying Matlab should complain a bit more when it comes to type conversions. Every now and then I have numbers in integer types and I want to keep them that way. However, Matlab tends to like to make them doubles every now and then and tracking down where it happens can be a pain.

    However, in the philosophy that Matlab should be math and not programming, I would have to say that warnings are sufficient. Calling it an error would be way overkill.

  8. Jayathissa K.E.I replied on :

    we want to more example.

  9. jai replied on :

    Hai guys,
    i am currently doing final year project using vision system. my project have to differentiate plastic and paper. I am using normal web-cam to capture the images.The programme that i am using is matlab version 7.0. I am now searching on how to differentiate it. Is there any commands in matlab that can help me in differentiating this two materials. I really want to know if there is any. Please if anyone know do help me.
    Thank you

  10. jai replied on :

    is there any command to differentiate plastic and paper using the image captured by matlab 7.0 and normal web-camera…plz help

  11. Daniel Armyr replied on :

    jai: How about you take a look at the Matlab file-exchange. There are loads of files there that do all sorts of things. If someone else has wanted to do that particular thing, there will probably be a script.

    On the other hand, maybe you should consider doing your own homework. This sounds very much like you are planning to plagiarize someone else’s work and hand it is as your own.

    –DA

  12. shasrin replied on :

    Hi, I want to know how to perform the arithmetic operation for two image? I have a problem for two image with different size.I really want to know is anyone has a sample coding for that?Plz…help me to find this kind of solution…tq

Leave a Reply


Loren Shure works on design of the MATLAB language at The MathWorks. She writes here about once a week on MATLAB programming and related topics.

  • J.B. Brown: Ah, and I am at fault for simply testing collinearity with the origin in the example above.
  • J.B. Brown: Indeed, > collinear( [0 3],[0 8],[0 -1e21+2e-15] ) ans = 1 > collinear( [0 3],[0 8],[0 -1e22+2e-15]...
  • OkinawaDolphin: Loren, thank you for telling me where to download timeit. Here are the two functions I just tested...
  • Loren: JB- It looks to me like Ilya’s solution and therefore yours are equivalent to the determinant. As Tim...
  • Loren: OkinawaDolphin, timeit can be downloaded from the File Exchange. Steve Eddins is the author. It does not ship...
  • OkinawaDolphin: It seems that neither R2007a nor R2007b have the function timeit, but I investigated computation time...
  • J.B. Brown: It would appear to me that Ilya Rozenfeld’s solution would be the cleanest. Just to help those who...
  • Loren: Markus- Congratulations on winning! And a nice illustration of how the size matters. Small enough, and the...
  • Markus: Hi Loren, which version is fastest also depends very much on the matrix dimensions. Look at my test function:...
  • Duncan: OkinawaDolphin, Regarding why your third example is slower than your second example, the result is in fact...

These postings are the author's and don't necessarily represent the opinions of The MathWorks.

Related Topics