Borrar filtros
Borrar filtros

Issue with saving real and imag values to a text file

4 visualizaciones (últimos 30 días)
Shannon Cherry
Shannon Cherry el 4 de Sept. de 2018
Comentada: Stephen23 el 4 de Sept. de 2018
I have two sets of data to be mapped onto a grid to their respective indices as shown in my below code. However, when I try to save the data to a text file, it is not considering the sign(+/-) of the imaginary value into account.
clc;
grid = zeros(4,2,1);
index_1 = (1:4)';
index_2 = (5:7)';
Data_1 = [1+1i,2-2i,-3+3i,-4-4i]';
Data_2 = [101+101i,202+202i,303+303i]';
grid(index_1) = Data_1;
grid(index_2) = Data_2;
fileID = fopen('SaveData.txt','w');
fprintf(fileID,'%i,%i\n',[grid(:),grid(:)]');
fclose(fileID);
Incorrect sign(+/-) is saved as shown below. If the real value is negative, it automatically considers the imaginary value also as negative. Could someone help me fix this.
1,1
2,2 % Expected : 2,-2
-3,-3 % Expected : -3,3
-4,-4
101,101
202,202
303,303
0,0
  1 comentario
Stephen23
Stephen23 el 4 de Sept. de 2018
A much simpler way of creating that matrix:
grid = [1+1i,2-2i,-3+3i,-4-4i;101+101i,202+202i,303+303i,0].'

Iniciar sesión para comentar.

Respuesta aceptada

Stephen23
Stephen23 el 4 de Sept. de 2018
Editada: Stephen23 el 4 de Sept. de 2018
You need to explicitly obtain the real and imaginary parts, before printing with fprintf:
M = [real(grid(:)),imag(grid(:))];
and then simply use this in fprintf:
fileID = fopen('SaveData.txt','w');
fprintf(fileID,'%i,%i\n',M.');
fclose(fileID);
The fprintf documentation states that "Numeric conversions print only the real component of complex numbers". So "Incorrect sign(+/-) is saved...": is not true: actually the negative sign is totally correct, for the real part of the number, which is exactly what you printed in your file.

Más respuestas (0)

Categorías

Más información sobre Data Type Conversion en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by