Multiple a matrix by every column of another matrix and stack the results in some form

1 次查看(过去 30 天)
Hello, I have a matrix A: 3xn and a matrix B: 3x6. What I wish to do is subtract each column of B from A as follows:
B_11 is subtracted from A_1i for i = 1:n, B_21 is subtracted from A_2i for i = 1:n, B_31 is subtracted from A_3i for i = 1:n.
This is repeated for each column of B with the whole A matrix and the results stacked each time, giving a resultant matrix that's 18xn.
Or storing the 3xn matrices for the 6 different B columns in a structure is also okay.
I have tried combinations of repmat but nothing useful yet. Can we do this without a loop, preferably?

采纳的回答

Voss
Voss 2022-3-14
I think this will do it:
n = 10;
A = 100+2*reshape(1:3*n,3,[])
A = 3×10
102 108 114 120 126 132 138 144 150 156 104 110 116 122 128 134 140 146 152 158 106 112 118 124 130 136 142 148 154 160
B = reshape(1:3*6,3,[])
B = 3×6
1 4 7 10 13 16 2 5 8 11 14 17 3 6 9 12 15 18
new_A = repmat(A,size(B,2),1);
new_B = repmat(B(:),1,size(A,2));
result = new_A-new_B;
disp(result);
101 107 113 119 125 131 137 143 149 155 102 108 114 120 126 132 138 144 150 156 103 109 115 121 127 133 139 145 151 157 98 104 110 116 122 128 134 140 146 152 99 105 111 117 123 129 135 141 147 153 100 106 112 118 124 130 136 142 148 154 95 101 107 113 119 125 131 137 143 149 96 102 108 114 120 126 132 138 144 150 97 103 109 115 121 127 133 139 145 151 92 98 104 110 116 122 128 134 140 146 93 99 105 111 117 123 129 135 141 147 94 100 106 112 118 124 130 136 142 148 89 95 101 107 113 119 125 131 137 143 90 96 102 108 114 120 126 132 138 144 91 97 103 109 115 121 127 133 139 145 86 92 98 104 110 116 122 128 134 140 87 93 99 105 111 117 123 129 135 141 88 94 100 106 112 118 124 130 136 142

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by