# If A is a 3x4 matrix, how do you find B if B=A(1:2)?

64 views (last 30 days)
Nate Pang on 16 Jan 2017
Edited: Niels on 16 Jan 2017
For example if A=[1 2 3 4; 5 6 7 8; 9 10 11 12]
B = A(1:2) = ???
And also how come the value of 1:2 in A(1:2, 2:3) is different than A(1:2)?

Niels on 16 Jan 2017
Edited: Niels on 16 Jan 2017
Hi Nate,
you have to be carefull by calling the contents of a matrix:
>> A=[1 2 3 4; 5 6 7 8; 9 10 11 12]
A =
1 2 3 4
5 6 7 8
9 10 11 12
1. if you refer to only 1 index such as A(1:2) the Matrix A is seen as vector whose colums are set one below another
>> A(:)
ans =
1
5
9
2
6
10
3
7
11
4
8
12
>> A(1:2)
ans =
1 5
2. if you refer to both index, you would just get what is to be expected: first index for row, and 2. for column
>> A(1:2,2:3)
ans =
2 3
6 7
if you intended to get the first two rows:
>> A(1:2,:)
ans =
1 2 3 4
5 6 7 8
to check if B is part of A, i cant think of a simple solution, but you could try to use ismember
but care the first output containing the true/false expression does not say if the exact same matrix is to be found in A but if each value in B is to be found in A:
>> A
A =
1 2 3 4
5 6 7 8
9 10 11 12
>> [yes_or_no,indices]=ismember(B,A)
yes_or_no =
2Ã—2 logical array % only if this matrix contains only 1s its possible
1 1 % that B can be inside of A
1 1 % on the other side only 1s does not necessarily means
indices = % that B is part of A (look at the example below)
4 7
5 8
2. example
>> B(2,1)=12
B =
2 3
12 7
>> [yes_or_no,indices]=ismember(B,A)
yes_or_no =
2Ã—2 logical array
1 1
1 1
indices =
4 7
12 8
this is no perfect solution, and if you use ismember you still are not done at this point, its just an idea

Albert on 16 Jan 2017
use function find, and your problem is solved. A=[1 2 3 4; 5 6 7 8; 9 10 11 12]; B = A(1:2); find(A==B(1)) >>1 which is the location of A==B(1) in matrix A.
A(1:2, 2:3) is different than A(1:2) A(1:2, 2:3) is short for A(1, 2), A(1, 3),A(2, 2), A(2, 3). A(1:2) is short for A(1, 1) and A(2, 1)
These are very basic and introductory knowledge, which you don't want to ask here.
Niels on 16 Jan 2017
for this Matrix A your solution may work, but imagine A had more than one 1 => the result wouldnt be unequivocal

Star Strider on 16 Jan 2017
MATLAB uses linear indexing for arrays, because the arrays are stored as consecutive elements in memory in column-dominant representation. So in your matrix, the first element in the vector is 1, the second is 5, the third is 9, the fourth is 2, and so on.
So:
B = A(1:2) = [1 5]
If you choose to explore this convention:
A = [1 2 3 4; 5 6 7 8; 9 10 11 12];
B = A(1:2)
[row,col] = ind2sub(size(A), (1:2))
row =
1 2
col =
1 1
so the [row,column] indices for â€˜A(1:2)â€™ are [1,1] (row #1, column #1) and [2,1] (row #2, column #1) respectively.