Hello, I hope you are doing well! I am not entirely sure how to succinctly describe the question I have, so I will instead demonstrate it.
Let's say I have two arrays:
A = [1 2 3];
B = [2 3];
I would like to do the operation A^B such that I would receive a 2D array C containing the solution of A.^B(1) and A.^B(2).
C(1,:) = A.^B(1);
C(2,:) = A.^B(2);
C = [1 4 9; 1 8 27];
I understand that I could write a For loop like this:
% Full Loop Code
A = [1 2 3];
B = [2 3];
C = zeros(length(B), length(A));
for i = 1: length(B)
C(i, :) = A.^B(i);
end
But I am interested in knowing how to do this using only vectors and not using a For loop. When I do:
C = A.^B
I receive this error:
Error using .^
Matrix dimensions must agree.
Any suggestions? I am using MATLAB 2016b.
Thank you!

 Réponse acceptée

Jan
Jan le 17 Juin 2021
A = [1 2 3];
B = [2 3];
C = A .^ (B.')

4 commentaires

Thank you so much for the quick answer! May I ask what the significance of the '.' in your code is? When I put B.' and B' in the console I get the same answer.
B.'
B'
ans =
2.0000e+000
3.0000e+000
If an array is real, the transpose (.') and conjugate transpose (') operators give the same results.
A = magic(3)
A = 3×3
8 1 6 3 5 7 4 9 2
B1 = A.'
B1 = 3×3
8 3 4 1 5 9 6 7 2
B2 = A'
B2 = 3×3
8 3 4 1 5 9 6 7 2
isequal(B1, B2) % Yes they are equal
ans = logical
1
If the array is complex they do not give the same result.
format shortg
C = A + 1i*(10-A)
C =
8 + 2i 1 + 9i 6 + 4i 3 + 7i 5 + 5i 7 + 3i 4 + 6i 9 + 1i 2 + 8i
D1 = C.'
D1 =
8 + 2i 3 + 7i 4 + 6i 1 + 9i 5 + 5i 9 + 1i 6 + 4i 7 + 3i 2 + 8i
D2 = C'
D2 =
8 - 2i 3 - 7i 4 - 6i 1 - 9i 5 - 5i 9 - 1i 6 - 4i 7 - 3i 2 - 8i
isequal(D1, D2) % these are not equal
ans = logical
0
Note the signs of the imaginary parts of D1 and D2.
@Alec Huynh: Thanks, @Steven Lord, for the explanation. An addition, why I've used .' in this case: For real arrays .' and ' produce the same result. It is a good programming practice to avoid assumptions of the inputs, so if I want to transpose the input, .' is the correct operator. Then I do not have to guess, if you (or any other use) is working with real or complex values.
This is the same strategy as e.g. specifying the dimension to operate on:
x = rand(randi(1:3, 2)); % e.g. [1,3], [2,1] or [3,2]
y = sum(x) % ?!? critical: input might be a column or row vector
y = sum(x, 1) % Avoid assumptions
The less assumptions the programmer includes in the code, the less likely is producing a bug or misleading output.
Alec Huynh
Alec Huynh le 25 Juin 2021
@Steven Lord, @Jan Thank you for the succinct explanations!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Produits

Version

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by