Subtracting Row and column vectors

13 views (last 30 days)
jack carter
jack carter on 13 Aug 2017
Answered: Akira Agata on 17 Aug 2017
I need to subtract vectors of different dimensions, "A" with dimension of (1x91)double and "B" with dimension of (60x1) double. In addition, there are two more vectors "C" with dimension of (1x119) double and "D" with dimension of (119x1) double.
How can I get (X=A-B) and (Y=C-D) in such cases?
  2 Comments
Akira Agata
Akira Agata on 13 Aug 2017
What do you mean by 'X=A-B'?
X(1) = A(1) - B(1), ..., X(60) = A(60) - B(60) ?
If so, what about X(61) to X(91) ?
I need the detailed definition of your calculation rule of 'A-B' and 'C-D'.
jack carter
jack carter on 13 Aug 2017
Edited: jack carter on 13 Aug 2017
Corresponding values should be subtracted like first value of A with first value of B, second of A with second of B and so on. I am aware that there will be remaining values as well because the dimensions are not the same. I am not sure what should be done with the remaining values as I shall run the simulation to check the result. I can do this after running each possible method.
What are the possible solutions for this case which you have mentioned X(61) to X(91)?
Same should go for C-D. I had same dimensions like mentioned here for C and D but at that time I needed to add both of them, so I transposed one to make the addition possible. This time I need to do the subtraction

Sign in to comment.

Answers (2)

Stephen23
Stephen23 on 13 Aug 2017
Edited: Stephen23 on 13 Aug 2017
One simple solution that does not require knowing anything about the sizes of the vectors:
>> A = randi(9,1,9)
A =
1 3 4 3 2 8 4 8 4
>> B = randi(9,6,1)
B =
7
4
8
7
4
2
>> C = diag(bsxfun(@minus,A,B))
ans =
-6
-1
-4
-4
-2
6
For newer MATLAB versions with implicit expansion:
diag(A-B)
Note that this is not particularly memory efficient so don't use this with large vectors!

Akira Agata
Akira Agata on 17 Aug 2017
I think the following would be one possible solution. By using zero-padding and transpose, I have adjusted A and B, C and D, to the same size.
%%Example of your data
A = rand(1,91);
B = rand(60,1);
% Adjut B to a row vector with the same length with A by zero padding
B1 = [B',zeros(1, length(A) - length(B))];
% Calculate X = A - B
X = A - B1;
%%Example of your data
C = rand(1,119);
D = rand(119,1);
% Adjust D to a row vector with the same length with C
D1 = D';
% Calculate Y = C - D
Y = C - D1;

Tags

Community Treasure Hunt

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

Start Hunting!