Subtracting Row and column vectors

조회 수: 12 (최근 30일)
jack carter
jack carter 2017년 8월 13일
답변: Akira Agata 2017년 8월 17일
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
Akira Agata
Akira Agata 2017년 8월 13일
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 2017년 8월 13일
편집: jack carter 2017년 8월 13일
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

댓글을 달려면 로그인하십시오.

답변 (2개)

Stephen23
Stephen23 2017년 8월 13일
편집: Stephen23 2017년 8월 13일
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 2017년 8월 17일
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;

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by