C++ to matlab(m-file) without mex

조회 수: 3 (최근 30일)
Pramit Biswas
Pramit Biswas 2015년 3월 16일
답변: Pramit Biswas 2015년 3월 17일
I have a C++ code:
#include <iostream>
#include <fstream>
#include <iomanip> // std::setfill, std::setw
using namespace std;
int main()
{
int i,j;
ofstream outfile;
outfile.open("testText.txt", ios::app);
outfile<< setfill('0');
for(i=0;i<2;i++)
{
for(j=0;j<12;j++)
{
outfile<<"XYZ"<<setw(2)<<i<<setw(2)<<j<<"\n";
}
outfile<<"\n";
}
outfile.close();
return(0);
}
Which will generate a text file like:
XYZ0000
XYZ0001
XYZ0002
XYZ0003
XYZ0004
XYZ0005
XYZ0006
XYZ0007
XYZ0008
XYZ0009
XYZ0010
XYZ0011
XYZ0100
XYZ0101
XYZ0102
XYZ0103
XYZ0104
XYZ0105
XYZ0106
XYZ0107
XYZ0108
XYZ0109
XYZ0110
XYZ0111
Need to create same output using matlab code.
Main problem:
setfill() alternative in matlab?
setw() alternative in matlab?
how
outfile<<"XYZ"<<setw(2)<<i<<setw(2)<<j<<"\n";
line can be replaced?
setw(): used to set field width of the next variable
setfill(): used to set fill character, what should be used to fill the width in setw.
Really need some help. Thanks in advance.

채택된 답변

David Sanchez
David Sanchez 2015년 3월 17일
Absolutely, You can:
i=10;
j=2;
option = '02';
str = strcat('XYZ%',option,'d%',option,'d\n');
fprintf(str, i, j)
XYZ1002
  댓글 수: 1
Pramit Biswas
Pramit Biswas 2015년 3월 17일
Waaooo.
That's a great trick. well done.

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Ken Atwell
Ken Atwell 2015년 3월 16일
You can use fprintf in MATLAB, which is closer in usage to C than C++:
>> i=1;
>> j=11;
>> fprintf('XYZ%02d%02d\n', i, j)
XYZ0111
  댓글 수: 1
Pramit Biswas
Pramit Biswas 2015년 3월 17일
Thank you very much for your really helpful answer.
using this code writing to the file is done;
setw() partially done; can we put those 02 as any variable, i mean if i want to change 02 to 03 automatically within the program?
using said command, fill will be always zero. what if I want to fill it with some other values? i.e. setfill() alternative?

댓글을 달려면 로그인하십시오.


Pramit Biswas
Pramit Biswas 2015년 3월 17일
final matlab code:
input1 = fopen('exp.txt','w');
fill = '02';
for i=0:1:1
for j=0:1:11
str = strcat('XYZ%',fill,'d%',fill,'d\n');
fprintf(input1, str, i, j);
end
fprintf(input1, '\n');
end
fclose(input1);

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by