Why are multiple, consecutive plusses allowable syntax in MATLAB? - matlab

Does anyone know why this works in MATLAB?
>> 1 ++ 2
ans =
3
Coming from coding in C, python, Java etc, I find it most counterintuitive that this should work at all. Presumably there's something important about the parser that I don't understand?

There's a difference between plus and uplus. I suspect MATLAB takes the first + as plus, and all the others as uplus. Since uplus is by default just "return what's behind", you add 1 and 2, and use a lot of "return what's behind" in between.
a=2;
c=+a % unitary plus
c =
2
1+2 % addition
ans =
3
1+++2 % addition and two uplusses
ans =
3
The reason uplus exists is to allow operator overloading in classes. The same works in other languages, e.g. in C#, to allow for operator overloading in confined classes.
The other reason mentioned in that C# thread is that is changes unsigned shorts to integers, which is not the case for MATLAB:
d=uint8(1)
d =
uint8
1
+d
ans =
uint8
1
a=+d
a =
uint8
1
It does, however, convert a boolean to a double, thanks to Cris Lunego for pointing that out:
+true
ans =
1
+false
ans =
0
The following however remains a mystery to me, inspired by Sanjay Manohar's comment:
>> [1 ++ 2]
ans =
1 2 % Two unary plusses
>> [1 + + 2]
ans =
3 % A normal plus and a unary one
>> [1++2]
ans =
3 % A normal plus and a unary one
The same works with multiple plusses, [1 +++..+++ 2], so with all plusses consecutively in the middle generates [1 2], all other combinations (as far as I tested) result in 3. I asked a separate question about this: Why do the plus and unary plus behave strange in array syntax?

Related

List declaration with/without bracket in matlab

For example, Why are 1:5 and [1:5] the same in matlab?
What is the reason behind this convention?
The reason for the convention is hard to tell without asking the creators of MATLAB, but here's a little insight. I apologies if this is a bit messy.
If you don't bother reading it all, here's the executive summary:
: is used to create regularly spaced vectors, while square brackets are used for concatenating.
First, you should know that even scalars are considered to be matrices in MATLAB. Scalars are simply 1x1 matrices, or to be more specific: 1x1x1x1x......1. There are in theory infinite amount of trailing singleton dimensions.
1 == [1] == [[[1]]]
Also:
a = 1;
a(1,1,1,:,:,1) %% Messy indexing showing how you can index a matrix using more dimensions than it appears to have.
ans =
1
The documentation says:
The colon operator is used to create regularly spaced vectors (and subscript arrays, and specify for iterations).
As scalars can be created without brackets, there's no reason you should need brackets around a clearly and unambiguously defined operator.
Brackets [] on the other hand creates vectors or matrices by concatenating values and vectors. From the documentation:
Square brackets are used in array construction and concatenation, and also in declaring and capturing values returned by a function.
Therefore, you can basically put brackets around anything you want. The same example as with the scalar above:
1:4 == [1:4] == [[[1:4]]]
Or around cells (doesn't change anything):
a = {3,1:4,'Hello, World!'}
a =
[3] [1x4 double] 'Hello, World!'
b = [a]
b =
[3] [1x4 double] 'Hello, World!'
Concatenating strings:
str1 = 'Hello';
str2 = ', World!';
str = [str1 str2]
str =
Hello, World!
Concatenating vectors:
[1:4, 6:8, 10]
ans =
1 2 3 4 6 7 8 10
If you had to put brackets around the 1:4 part, this would be (also works, but much more cumbersome):
[[1:4], [6:8], 10]
ans =
1 2 3 4 6 7 8 10
A possible reason for the convention:
It would be inconsistent if you needed brackets around 1:3.
Unrelated: For anyone used to other programming languages, brackets inside brackets often means you "go up" one dimension. Therefore, this might be confusing to some.
Well in a way they are and are not the same , In MATLAB every thing is a matrix , even
a = 5
is 1x1 matrix , for 1-D matrix or vector they will perform the same operation
when you write
>> x=1:3
ans =
1 2 3
MATLAB consider the matrix as one dimensional , like for instance in the example below it consider only the last row of the declaration
>> x=1:3;2:4
ans =
2 3 4
but when you specify brackets it can be an nxm dimensional matrix
>> x=[1:3;1:3]
x =
1 2 3
1 2 3

behavior of colon operator (:) with matrix or vector arguments

We all know the matlab colon operator to create a linear sequence, i.e.
1:5 = [1 2 3 4 5]
Now I found that the arguments of the colon operator can also be applied to vectors or matrices. However I do not understand the definition behind.
Examples
[1 2 3 4]:5 == [1 2 3 4 5]
[1 2; 3 4]:3 == [1 2 3]
Why is this?
The second argument can be vector or matrix as well.
Ultimately I would like to understand sequences such as
1:2:3:4:5
which is fully legal in matlab and [1 5] by the way!
Note 1:2:3:4:5:6 is left associative i.e. parsed as ((1:2:3):4:5):6.
So what is the behavior for the colon operator with matrix/vector arguments?
EDIT: corrected the statement of left associativity.
The documentation for the colon operator says:
If you specify nonscalar arrays, MATLAB interprets j:i:k as j(1):i(1):k(1).
Your first example is interpreted as 1:3, the second as 1:5
Expressions with more than two : are parsed left-associative:
a:b:c:d:e==(a:b:c):d:e
.
>> 1:2:3:4:5
ans =
1 5

Dividing by a range values

I am a bit confused with the below output:
>> 1:6/3
ans =
1 2
But
>> 1/3
ans =
0.3333
Also
>> 1:24/3
ans =
1 2 3 4 5 6 7 8
It seems like MATLAB is outputting only values of number divisible in range 1-24 by 3? But why not for those which are not fully divisible by 3?
Also I am not able to understand the below output:
>> 1:24/3:2
ans =
1
Similarly
>> 1:6/2 * 2
ans =
1 2 3 4 5 6
It's simple enough:
1:6/3 implies 1:2 which is a vector ranging from 1 to 2.
1/3 is simply a straight forward division.
1:24/3 implies 1:8 which is a vector ranging from 1 to 8.
1:24/3:2 implies 1:8:2 which is a vector ranging from 1 to 2 with a difference of 8 between each element. This just leaves you with 1 as the next possible iteration, 9 would be greater than 2.
1:6/2 * 2 implies 1:3*2 which implies 1:6. This is a vector ranging from 1 to 6.
This is an operator precedence problem. / has higher precedence level than :.
Therefore 1:6/3 is equivalent to 1:(6/3), while you wanted to compute (1:6)/3
Try with parenthesis to observe different results:
>> (1:6)/3
>> (1:24)/3
>> (1:24)/(3:2)
>> ((1:6)/2)*2
You might be aware of the BODMAS rule which says that the
B Brackets first
O Orders (ie Powers and Square Roots, etc.)
DM Division and Multiplication (left-to-right)
AS Addition and Subtraction (left-to-right)
When modified to the usage in mathematics it added a few more operators according to which / has a higher precedence over :
Therefore you get erroneous results. You can check this thing by implementing more brackets.

Doing operations between subsequent elements without using a FOR loop?

In Matlab, Is it possible to do simple operations between subsequent elements of an array without using a for loop? Something like diff(). For example, I have this vector:
A = [2 4 8 16 32]
and I want each element to be divided by its predecessor:
ans = [2 2 2 2]
How can I do it without going through all elements (without using loops)?
You can use the fact that division in Matlab work on both scalars and matrices, if you use the ./ operator rather than /
>> A = [2 4 8 16 32];
>> A(2:end) ./ A(1:end-1)
ans =
2 2 2 2
Regarding your question about doing dot() between vectors stored in the rows of a matrix. There is an additional argument to dot() that tells it whether your vectors are stored in columns (the default) or rows;
>> x = rand(3);
>> y = rand(3); # random vectors
>> dot(x,y) # dot product of column vectors
ans =
0.5504 0.5561 0.5615
>> dot(x,y,2) # dot product of row vectors
ans =
0.3170
1.0938
0.2572
Most functions in Matlab are vectorized so that they can work on scalars, vectors and matrices, but you sometimes have the read the documentation (e.g. type help dot) to work out how to use them.

how to compare matlab cells or structs [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Octave/MATLAB: How to compare structs for equality?
is there a simple comparison function for matlab cell or struct objects?
using '==' doesn't seem to work :(
If you want to know if two cell arrays or struct objects are exactly equal you could always use isequaln.
Use isequal to compare two cells. Note however that == is not advised even for arrays:
>> A = [1 2 3 4 5];
>> B = [1 2 3 4 5];
>> A == B
ans =
1 1 1 1 1
You would need to use a further trick to use that expression in a if statement for instance.
The reason == is not recommended for variables of type double is because of the IEEE 754 representation use by MATLAB. For instance:
>> .1 + .1 + .1 == .3
ans =
0
To compare double values more robustly, you can use the abs function in MATLAB:
>> if ( abs( (.1+.1+.1) - .3 ) < 1e-10 ); disp('Values are pretty close although not necessarily bit equal'); end
Values are pretty close although not necessarily bit equal
>>