I want to show a complex matrix in polar form in Matlab, however all the complex numbers are printed in rectangular form, for example:
\>> sqrt(2)*[1-1i 1+1i; 1i -1] ans = 1.4142 - 1.4142i 1.4142 + 1.4142i 0 + 1.4142i -1.4142
Is there a way to print complex numbers in polar form? Something like this:
\>> sqrt(2)*[1-1i 1+1i; 1i -1] ans = 2.0000
It can be a function also, I just want to know if something like this has already been made. Thanks.
Daniel Turizo
asked Mar 2, 2015 at 0:17
Daniel Turizo Daniel Turizo
182 2 2 silver badges 9 9 bronze badges
To build on what Luis Mendo was talking about, I don't believe there is a utility in MATLAB that prints out a complex number in polar form. However, we can use abs and angle to our advantage as these determine the magnitude and phase of a complex number. With these, we can define an auxiliary function that helps print out the magnitude and phase of a complex number in polar form. Something like this:
function out = polarPrint(A) absA = abs(A); phaseA = angle(A)*180/pi; out = arrayfun(@(x, y) sprintf('%f < %f', x, y), absA, phaseA, 'uni', 0);
Place this in a file called polarPrint.m so that you can call this in MATLAB whenever you need it. The first and second lines of code determine the magnitude and phase of a complex number stored in absA and phaseA respectively from an input matrix A that is numeric. If you want it in degrees, you simply multiply by 180 / pi . The third line is the most magical. We simply go through each element in absA and phaseA , print each to a string using sprintf with a < separated between the two numbers and this string is placed in a cell array. arrayfun goes through every element in an array and applies a function to this element. In this case, I will let arrayfun go through two arrays simultaneously, which will be the magnitude and phase of each number in A . As such, I'm going to use absA and phaseA as inputs into this function I want to apply to each of these elements. The uni = 0 flag means that the output is not numeric but it will be a cell array of non-numeric outputs (i.e. strings in our case).
out will contain a cell array of strings that is the same size as A that you can print out and examine yourself.
Using Luis Mendo's example, we get:
>> A = sqrt(2)*[1-1i 1+1i; 1i -1]; >> out = polarPrint(A) out = '2.000000 < -45.000000' '2.000000 < 45.000000' '1.414214 < 90.000000' '1.414214 < 180.000000'