List declaration with/without bracket in matlab - 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

Related

Why are multiple, consecutive plusses allowable syntax in 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?

Matlab: Is there any difference between the use of square brackets for declaring a list or not?

We can specify a list by a = [1:3]
but at the same time,
we can also specify a list by a = 1:3.
I see that the output on the command window for a is the same, i.e.
a =
1 2 3
But is there any difference in the internal structure where we cannot see and cause difference in further calculation?
I don't think so. In MATLAB, the square brackets can be used for concatenating some number of matrices together. So for example, I could do
x = [1:2, 5:7, 9:12]
x =
1 2 5 6 7 9 10 11 12
In your case, you are doing matrix concatenation with only one matrix, which simply yields the matrix provided.
You don't even need to go to vectors. Even for scalars, the following are equivalent:
a = 123;
a = [ 123 ];
The first one declares a as the scalar 123, while the second one declares it as a length-1 vector whose sole element is 123. In MATLAB, these two are exactly the same thing.
Here's an example (using octave):
octave:1> x = 123
x = 123
octave:2> x(2) = 456
x =
123 456
As you can see, what was declared as a scalar could very easily be handled as a vector. I think everything is just stored as vectors.

for loop in matlab storing values (scalar times vector array)

I would like to know in matlab how to accomplish the following task:
If i have a for loop like in the following lines:
b=[1 2 3 4];
for i=1:1:10
x=i.*b
end
the code iterates i-times multiplying a scalar times the vector b; but if i put in the for loop x(i) in order to store the resulting vector of every iteration, i wouldn't get what i'm looking for. What i'm lookig for is to get:
x(1)=[1 2 3 4]
x(2)=[2 4 6 8]
... and so on
As in P0W's answer, you need a two-dimensional matrix to store "a vector of vectors". You can't use x(n), since addresses a single value in a one-dimensional matrix.
Another solution, maybe closer to what you want, is to use cell a cell array, which allow to create a matrix containing mixed-typed values (so you can put vectors too!). They are quite similar to regular array, but you need curly brackets:
b=[1 2 3 4];
x = cell(1,10); % preallocating, not necessary but always a good idea
for i = 1:10
x{i} = i*b % notice the curly bracket with the index
end
note: you don't need the .* operator, since is a scalar-matrix multiplication.
You can get back your values with
x{1} = [1 2 3 4] % again curly brackets
x{2} = [2 4 6 8]
...
Can use:
x=[1:10]'*b
then
x(1,:)
x(2,:)
etc

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.

Combination of colon-operations in MATLAB

I have a question concerning the colon operator and expansion of vectors in MATLAB. My problem is to understand how the following line of code expands, to be able to use it for other sequences. The line of MATLAB code is:
a(1:2:5) = 1:-4:-7
Note that a is not defined before the expansion. This returns the vector
a = 1 0 3 0 -7
I know how the colon operator works with {start}:{step}:{stop}, my problem is to understand how and why the combination of a(1:2:5)and 1:-4:-7 returns a vector of five elements with zeros in position 2 and 5?
Whenever Matlab detects you're indecing to an element outside the current bounds of the matrix/array, it will automatically pad the missing elements with zeros:
>> clear b; b(10) = 5
b =
0 0 0 0 0 0 0 0 0 5
This feature is both very useful, and very dangerous. It is useful for the fact declarations can be made very easy, such as your own case. You can create a whole array of custom-made classes by issuing something like
myClassArray(500) = myClass(1, 2);
which is infinitely better than something like
% cannot pre-allocate (zeros() or ones() give double/uint8/..., not myClass)
for ii = 1:499
myClassArray(ii) = myClass; % so, growing array
end
myClassArray(500) = myClass(1,2);
But, growing arrays can be hard to spot:
a = zeros(10,1);
for ii = 1:10
a(ii+1) = rand;
end
which can make performance drop tremendously. Also, when you translate code prototyped in Matlab to a statically-typed language like C++, copying this code will result in buffer overflows and thus segfaults.
Now, going back to your case:
clear a; a(1:2:5) = 1:-4:-7
The 1:2:5 will expand to the array [1 3 5], and the 1:-4:-7 will give the values [1 -3 -7]. Since the variable a does not exist yet, Matlab will create a new one and fill the elements [1 3 5] with the values [1 -3 -7]. The indices that have been skipped in order to initialize variable a (namely, [2 4]) will then have been initialized automatically to zero.
If you're familiar with Python, it's a bit like the syntax to assign multiple values to multiple variables
x,y = 1,2
But in your Matlab case, these different variables are indices to a non-existent array, which requires "filling the holes with something" to make it a valid, consistent array.
Does this make things clear?
when you define a(1:2:5), it creates a size 5 vector (zero-valued), and selecting odd indexed(3 of them exists) cells. 1:-4:-7 creates three values (not five). Finally your selected three cells are filled with data of 3 values coming from 1:-4:-7