what is the meaning of this operation?

9 views (last 30 days)
If you have a matrix d=[1 2 3 4; 5 6 7 8 9; 10 11 12 13]; what is the meaning of d(1 2) and d([1 2])
Thank you.

Accepted Answer

Ameer Hamza
Ameer Hamza on 5 Nov 2020
Edited: Ameer Hamza on 5 Nov 2020
In MATLAB, the matrix cannot have a different number of elements in a row, so I have modified matrix d as follow
d = [1 2 3 4; 5 6 7 8; 10 11 12 13]
For your question, d(1 2) is invalid in MATLAB. I guess you meant d(1,2), which means access the element in 1st row and 2nd column of matrix 'd'. If you print matrix 'd', you will get
>> d
d =
1 2 3 4
5 6 7 8
10 11 12 13
and
>> d(1,2)
ans =
2 % element in 1st row and 2nd column
The syntax d([1 2]) uses linear indexing. Read about linear indexing here: https://www.mathworks.com/company/newsletters/articles/matrix-indexing-in-matlab.html. Espically refer to the image after the line "Here are the elements of the matrix A along with their linear indices".

More Answers (2)

Monika Jaskolka
Monika Jaskolka on 5 Nov 2020
Firstly, d is an invalid matrix because it must have consistent dimensions. The second row has 5 elements whereas the rest have 4.
d(1 2) is an invalid expression.
d(1, 2) is the element in the row 1, column 2.
d([1, 2]) returns 2 elements. The elements in positions (1,1) and (2,1). You can access matrix elements both my specifying their row & col numbers (like your first example), but also by just providing a linear index value.

William
William on 5 Nov 2020
Melin,
The matrix d has an error in it, because the 2nd row has more columns than the 1st and 3rd row. But, supposed we use d = [1,2,3,4; 5,6,7,8; 9,10,11,12]. In this matrix, d(1,2) will refer to row=1, col=2, and so will have the value d(1,2)=2. The notation d(1 2) does not have any meaning in Matlab. The notation d([1 2]), however, is more interesting. It refers to the elements d(1) and d(2). Although d is a 2D matrix, you can also address its elements with a 1-dimensional index, and in this case the elements are numbered from top to bottom of each column, from the first column to the last. In the case of matrix d, we have d(1)=1, d(2)=5, d(3)= 9, d(4)=2, and so on until we get to d(12)=12. So, d([1 2]) = [d(1) d(2)] = [1 2]. Likewise, if we wrote d([7 9 11]) or d([7,9.11]) it would mean [d(7), d(9), d(11)] = [3, 11, 8].

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!