MATLAB: Negative Numbers to the power of 0

depthnegative numbers

Hi All,
New-again matlab user after a decade away; having trouble with raising a negative number to the power 0.
I recognise that:
  • (-2)^0 = 1 and
  • -2^0 = -1.
In my code, I am trying to populate a 5×5, row by row filling the columns with elements of one 1×5 row vector to the power of another 1×5 vector.
I have written a very basic, and probably inefficient way of doing this with two for loops, but when it comes to raising a negative number to the power 0 and storing it, I get 1 as opposed to what I think is correct; -1.
I presume Im missing something very basic but would really appreciate any help; Thank you!
k = [0:4]
x = [-2.0 3.0 9.0 2.0 25.0]
A = ones(5,5);
for row = 1:length(k)
for col = 1:length(k)
A(row,col) = x(col)^k(row);
end
end
This is what I get: But I think the top left should be -1 since -2^0 = -1
1 1 1 1 1
-2 3 9 2 25
4 9 81 4 625
-8 27 729 8 15625
16 81 6561 16 390625

Best Answer

You can do it without for-loop
k = 0:4;
x = [-2.0 3.0 9.0 2.0 25.0];
A = x.^(k.')
Also, x(col)^k(row) is equivalent to (-2)^0, not -2^0.
For example, what you you expect the output of following code to be
x = -2;
y = x^2
should y be 4 or -4?