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.
- 범주:
- Common Errors,
- Travel