How do I make a column vector to add to my original matrix?

조회 수: 5 (최근 30일)
Connor
Connor 2023년 2월 5일
답변: Voss 2023년 2월 5일
Im trying to solve this: You want to add 4 to each element in the first row of A, subtract 1 from each element in the second row of A, and keep the third row as-is. Create a column vector that you can add to A to perform this task. Call your column vector B.
I have the matrix: A = [1 3 5; -10 -8 -6; (sin(pi/2)) 5^3 (exp(-2))]
I then did:
A = [1 3 5; -10 -8 -6; (sin(pi/2)) 5^3 (exp(-2))]
A = 3×3
1.0000 3.0000 5.0000 -10.0000 -8.0000 -6.0000 1.0000 125.0000 0.1353
B_one = A(1,:) + 4
B_one = 1×3
5 7 9
B_two = A(2,:) - 1
B_two = 1×3
-11 -9 -7
B_three = [(sin(pi/2)) 5^3 (exp(-2))]
B_three = 1×3
1.0000 125.0000 0.1353
B = [B_one B_two B_three]'
B = 9×1
5.0000 7.0000 9.0000 -11.0000 -9.0000 -7.0000 1.0000 125.0000 0.1353
I am trying to make the column vector but my column vector is never the right size and I keep getting the error: Variable B must be of size [3 1]. It is currently of size [9 1]. Check where the variable is assigned a value.

채택된 답변

Torsten
Torsten 2023년 2월 5일
이동: Torsten 2023년 2월 5일
What about
B = [4;-1;0]
?

추가 답변 (1개)

Voss
Voss 2023년 2월 5일
A = [1 3 5; -10 -8 -6; (sin(pi/2)) 5^3 (exp(-2))];
B_one = A(1,:) + 4;
B_two = A(2,:) - 1;
B_three = [(sin(pi/2)) 5^3 (exp(-2))];
In constructing B from B_one, B_two, B_three, use vertical concatenation by separating the rows with semicolons, and avoid transposing the result:
B = [B_one; B_two; B_three]
B = 3×3
5.0000 7.0000 9.0000 -11.0000 -9.0000 -7.0000 1.0000 125.0000 0.1353
You can construct a column vector the same way, using vertical concatenation, which can then be added to A. Example:
A = magic(3)
A = 3×3
8 1 6 3 5 7 4 9 2
to_add = [2; 5; -9] % this column vector will be used to add 2 to the first row of A, 5 to the 2nd, -9 to the 3rd
to_add = 3×1
2 5 -9
B = A + to_add
B = 3×3
10 3 8 8 10 12 -5 0 -7

카테고리

Help CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by