MATLAB: If A is a 3×4 matrix, how do you find B if B=A(1:2)

matrixscript practice

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)?

Best Answer

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