简体   繁体   中英

writing a vector from c++ code into a file and then reading it in matlab

I have a vector of data type double generated in c++ and I am trying to write it into a text file so that I can then load the text file into matlab in order to plot the data from the vector versus data that is already in my matlab workspace. I am able to create a file called real_data2.txt, and the program runs without an error, but then when I try to load the file in Matlab or open it in a text reader, the contents of the file is gibberish so-to-speak. The code that I am using to create the file is:

ofstream out("real_data2.txt");
    if(!out){
        cout << "Cannot open file.\n";
        return;
    }
for(int i = 0; i<N; i++){
    out.write((char *) &out2[i][0], N);
}
out.close();

where N is the length of out2. This successfully generates the 'real_data2.txt' file. I then put the generated file into the matlab path and use A = textread('real_data2.txt' ) in matlab to try to read the file. The error message that I receive is:

Error using data read Trouble reading number from file (row 1, field 1) ==> ?> Uíl¯9@9ÊÝÖ(@9Ò»=£P<@¨CÁ\\n

Error in textread (line 175) [varargout{1:nlhs}]=dataread('file',varargin{:}); %#ok

and when I double click the txt file I get a file containing text like:

?>Uíl¯9@9ÊÝÖ(@9Ò»=£P<@¨CÁ

' C@Bw|?N¯8@]H~=@7@7ÂÙjó?õ?ñXéWSO@¹U¥A° õ¿»D¾;@@¡ԨÊëQÀw®nr!úU@ß?7XÀjw©}NÀJA(×FÀ|ûó>%÷GÀa¬W¯7@·âÖ3Ð ÀÉ¿ x¨G@Ï¿U°ÜÁ6@ò5^->@qzáme[ÀKÆ]T^'À¼7CJK@EhúôP:ÀF¼¸ý@íÀ÷¾§ÎC@2w©^=AÀÛ«½ñðúr@ >ò(÷@B˶xÀË6Y7¸@s÷ãCÀ<µ} lÀ<uÄòÚtÀêGÂ0KZÀ~iò*~@$áu@Àq >¢Ò E{@Õbp«^8DÀ4©@Ëçc@nê'È1ÀÑJ?5|@?$éEy ÀUßÎzí@,u°<ä@^Q4íbÀ4õÆÚ@6S8(*ÀD$°ä?u@kn|½Àz >ÓvÀ'F@ôuc@þÃjàÂ:À KµÕv@ý/ú?ÁL]Àv°¶ó+R@íæ¿¥òC@ðvwjc@WÔÙjÀ¡ @y¿ò5d®I@M¸ö/þät@?ZÝd>@Cåh0~ÀLÛoE@cܼ¥À§ÝY.^Àù}øDzÀß®H\\XÀ¦ähöT~@ÍÚ\\åþÀá@Êà¤Ï»TÀAýx@r$Ü@u@Bã¿ l@?ß xç@½ô¶ %ÖbÀ{̱Àò#@HëSuÀ[ÙÑóÏ)w@ zû%ÀGK«7qiÀŦÊoÀúxeIÀy8nÓV@ØÕ3~yÀ³ >ú¹@vc@ñáĶmÀ &Q¹ig@?klgmÀ`Ìh&ûu@J «?kGiÀÂ|7kê@?y- @ªôg@ïíEY@\\Ayi?S\\@eظhã@ðô6fzÀ ©ås¬·@ROÅÍjÀÓâÒ×SJ Àýßv¨b >À(Ê- ߸Àów Ás@û?öÅèÀj¦Ðî@© ÎÀ¾&ñ~.U@_ÿz<~@qådøIÛz@4 )Áe@:´ N?{À=ào¸@ÆlëíVÒÀ©ÀÍûY7|XÀ¬' Çä1ÀØ@Á?Çj@®¨k8À¨

Any ideas where I am going wrong? I don't know much about this topic, but I am assuming that it has something to do with trying to cast the location of the data to a char pointer but I am not sure and wouldn't know how to get around that since I have tried altering that line unsuccessfully with things like out.write((char *) out2[i][0], N); and out.write((double *) &out2[i][0], N); which I realize now might not make too much sense...Anyways, any help would be greatly appreciated! Let me know if you know how to fix this problem!

out << out2[i][0];

is the correct way.

Your output is binary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM