printing matrix with real and complex numbers
Mostrar comentarios más antiguos
I have a matrix containg some real numbers and some imaginary numbers (eigenvalues).
I used following code to print to file
fprintf(fid,'%f %f\n',real(eigenValues), imag(eigenValues));
This code is ok if all are imaginary numbers. When some elements are only real, this code takes adjacent element and says that it is a imaginary. For eg.
Eigenvalue=
-203.122425981375 + 0.00000000000000i
-0.378775249508577 + 81.5733975555839i
-0.378775249508577 - 81.5733975555839i
-1.52421833698961 + 58.2049500388907i
-1.52421833698961 - 58.2049500388907i
-2.35088199995723 + 20.1918127788066i
-2.35088199995723 - 20.1918127788066i
-10.5006520053745 + 0.00000000000000i
But output to the file is
-203.122426 -0.378775
-0.378775 -1.524218
-1.524218 -2.350882
-2.350882 -10.500652
0.000000 81.573398
-81.573398 58.204950
-58.204950 20.191813
-20.191813 0.000000
Please help. fast.
Respuestas (2)
Walter Roberson
el 4 de Dic. de 2013
Your code is not correct even if everything has non-zero imaginary coefficients. You need
fprintf(fid,'%f %f\n',[real(eigenValues(:)), imag(eigenValues(:)].' );
This code can be simplified if it is known for sure that eigenValues is a row vector. In that special case,
fprintf(fid,'%f %f\n',[real(eigenValuess); imag(eigenValues)] );
Remember, fprintf goes down columns when determining what to print next.
1 comentario
Walter Roberson
el 9 de Dic. de 2013
You didn't really say what you wanted to do with the larger matrix that combines real and imaginary values, so I had to guess. This code notices when entire columns are real-valued and omits printing the imaginary parts for those columns.
Letting your matrix be MAT,
formats = {'%f\t', '%f %+fi\t'}; %you can use ' ' instead of '\t'
rMAT = real(MAT);
iMAT = imag(MAT);
needs_imag = any(iMAT); %columnwise test if any imaginary component
T = formats(needs_imag + 1); %those ones get different format
fmt = [T{:}];
fmt(end) = sprintf('\n');
jointMAT = reshape([rMAT; iMAT], size(MAT,1), []);
jointselector = reshape( [true(1,size(MAT,2)); needs_imag], 1, []);
joint_to_emit = jointMAT(:, jointselector);
fprintf( fmt, joint_to_emit.' );
nirmal joshi
el 9 de Dic. de 2013
Editada: Walter Roberson
el 9 de Dic. de 2013
Categorías
Más información sobre Matrices and Arrays en Centro de ayuda y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!