user2413711
user2413711

Reputation: 85

Matlab complex matrix magnitude

I have a matrix S something like:

1  4  7
2  5  8
3  6  9

Then I make a=complex(S{2},S{3}) and wanted to find the abs(a);. This is not possible in MATLAB as a is not an integer - it is a matrix. How can I get the magnitude of each row of matrix a?

PS: the matrix is read from a text file using textscan() as S = textscan(fileID,'%d %d %d', 'delimiter','\t');.

Second question:

Assuming again hav the following S matrix.

1  4  7  2  1
2  5  8  3  4
3  6  9  6  8 

Now I wanted to arrange them in such way that column 2,3 and 4,5 alternate like this:

4  2
7  1
5  3
8  4
6  6
9  8

How can I do that without using a loop? Thanks.

Upvotes: 1

Views: 1704

Answers (1)

rayryeng
rayryeng

Reputation: 104484

Going with my assumption in the comments, I'm going to assume that the second column consists of your real component of your matrix while the third column consists of your imaginary components. Your matrix S is actually a cell array of elements. You don't need to use complex then abs. You can simply take each of the columns, individually square them, add them together and take the square root. What I would do is convert the cell array into a 2D matrix, cast it to double to allow for floating point precision when finding the magnitude, and do what I just did above. This is necessary because abs and sqrt will only work for floating-point numbers. Your elements in S are already int32 due to the %d delimiter from textread. In other words:

Smat = double(cell2mat(S));
realComp = Smat(:,2);
imagComp = Smat(:,3);
mag = sqrt(realComp.^2 + imagComp.^2);

mag will thus return the magnitude of each row for you, assuming that the second column is the real component and the third component is the imaginary component as we specified.


However, if you're dead set on using complex and abs, you can do it like so:

Smat = double(cell2mat(S));
imagNumbers = complex(Smat(:,2), Smat(:,3));
mag = abs(imagNumbers);

This should still give you the same results as we talked about above.


Edit

Seeing your edit in your post above, we can achieve that quite easily by subsetting the matrix, then applying reshape to each part of the matrix you want. In other words:

Smat = double(cell2mat(S));
realMat = Smat(:,2:3); %// Grab second and third columns
imagMat = Smat(:,4:5); %// Grab fourth and fifth columns
realCol = reshape(realMat.', [], 1); % // Form the columns like you specified
imagCol = reshape(imagMat.', [], 1);

finalMatrix = [realCol imagCol];

finalMatrix should contain those two columns that you specified above in a single matrix.

Upvotes: 2

Related Questions