How can I export variable to a text file in mex file ?
Show older comments
Dear Friends,
I am working MATLAB Version 7.6.0.324 (R2008a) with Microsoft Visual C++ 2010 compiler.
I want to export my variable to a text file, here some lines of my c file:
/* amsubread6.c - MATLAB mex file for reading AMSU-B data
/* Usage: amsub = amsubread6(amsubfile)
#include "mex.h"
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#define NUM_CHANNELS 5
.
.
.
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
mxArray *tb_mat, *lat_mat, *lon_mat;
double *tb[NUM_CHANNELS], *lat, *lon;
int dims[2] = {NUM_CHANNELS, 1};
.
.
.
tb_mat = mxCreateCellArray(2, dims);
mxSetCell(tb_mat, channel, mxCreateDoubleMatrix(num_spots,num_scans, mxREAL));
tb[channel] = mxGetPr(mxGetCell(tb_mat, channel));
mxSetFieldByNumber(plhs[0], 0, 0, tb_mat);
lat_mat = mxCreateDoubleMatrix(num_spots,num_scans, mxREAL);
lat = mxGetPr(lat_mat);
mxSetFieldByNumber(plhs[0], 0, 1, lat_mat);
lon_mat = mxCreateDoubleMatrix(num_spots,num_scans, mxREAL);
lon = mxGetPr(lon_mat);
mxSetFieldByNumber(plhs[0], 0, 2, lon_mat);
.
.
.
How can I export tb[], lat, lon to a text file like this format :
lat lon tb[1] tb[2] tb[3] tb[4] tb[5]
Thanks for your help
Answers (1)
José-Luis
on 16 Aug 2012
Hello!
#include <iostream>
#include <fstream>
using namespace std;
ofstream myfile;
myfile.open ("my_file.txt");
//A loop will probably required here
myfile << "lat" << " " << "lon" << " " << val1 << " " << [...] << endl;
myfile.close();
Cheers!
5 Comments
hadi
on 18 Aug 2012
Edited: Walter Roberson
on 18 Aug 2012
Walter Roberson
on 18 Aug 2012
What file extension did you save the code as? <fstream> and other aspects of the code shown are for C++ and would not compile if saved to a .c file. Your original code is C code.
hadi
on 18 Aug 2012
José-Luis
on 18 Aug 2012
True, the my answer was C++. If you want plain C, then you can use fopen and fprintf.
hadi
on 27 Aug 2012
Categories
Find more on Text Files in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!