Write urdu in notepad file using matlab - matlab

I have a Urdu Optical character Recognition. When I convert my image text to Unicode and write it in notepad file it shows like "ÌÇ Ûã ˜Ç äíÇ ÝÑ " not in urdu language. Here is my code
disp(native2unicode(rst))
f = fopen('temp.txt', 'w', 'native', 'UTF-8');
s = char(native2unicode(rst));
fprintf(f, ' %s.\r\n', s);
fclose(f);

The following code runs fine on my system. Maybe the added 'UTF-8' parameter helped?
rst='اردو‎';
disp(native2unicode(rst,'UTF-8'))
s = char(native2unicode(rst,'UTF-8'));
f = fopen('temp.txt', 'w', 'native', 'UTF-8');
fprintf(f, ' %s.\r\n', s);
fclose(f);

Related

Ghostscript ps2pdf not Working Correctly from MATLAB

I have a .tex file I am attempting to write from a MATLAB environment (2017b) using first latex, then dvips, and finally ps2pdf to create the PDF file. The PDF file is properly created when I run it through TeXWorks, but sends an error from ps2pdf when I try to run it through. I'm not entirely sure what's wrong with the way I send it to the command line. Here is the script I am attempting to run.
set(groot, 'defaultAxesTickLabelInterpreter','latex');
set(groot, 'defaultLegendInterpreter','latex');
set(0,'defaultTextInterpreter','latex');
addpath('C:\Program Files (x86)\MiKTeX\miktex\bin\x64')
exampledir='\\our\server\';
examplefilename='test';
texdoc=fullfile(exampledir,strcat(examplefilename,'.tex'));
auxdoc=fullfile(exampledir,strcat(examplefilename,'.aux'));
logdoc=fullfile(exampledir,strcat(examplefilename,'.log'));
dvidoc=fullfile(exampledir,strcat(examplefilename,'.dvi'));
psdoc=fullfile(exampledir,strcat(examplefilename,'.ps'));
pdfdoc=fullfile(exampledir,strcat(examplefilename,'.pdf'));
fileID = fopen(texdoc,'w');
textext=['\documentclass[twoside]{article} %Two-sided document. Required for fancyhf left and right page numbering scheme current.' newline ...
'\usepackage{graphicx}' newline ...
newline ...
'\usepackage{fancyhdr} %Use the package fancy header/footer' newline ...
newline ...
'\usepackage[letterpaper,margin=0.5in,bottom=0.75in,top=0.7in]{geometry} %Ensure the paper is letterpaper.' newline ...
'\usepackage{grffile}' newline ...
'\usepackage{caption}' newline ...
'\usepackage{float} %Float used to position graphics.' newline ...
'\usepackage{lastpage209} %For last page' newline ...
newline ...
'\DeclareGraphicsExtensions{.PDF,.jpg} %Notify LaTeX what type of graphics extensions to expect.' newline ...
newline ...
'\renewcommand{\headrulewidth}{0pt} % remove the header rule' newline ...
newline ...
'\fancyhf{} % clear all header and footers' newline ...
newline ...
'\pagestyle{fancy} %Use the fancy pagestyle, which will include the fancy header and footer options we defined above.' newline ...
newline ...
'\setlength\headheight{38pt} ' newline ...
newline ...
'\fancyhead[L]{{Page \thepage} of \pageref{LastPage}} %Left side on even pages; right side on odd pages.' newline ...
'\fancyhead[R]{\includegraphics[trim={0.3in 0.26in 0.05in 0.26in},clip,width=0.4in]{{\\our\server\mypicture}}}' newline ...
newline ...
'\begin{document} %This will be the actual document and what goes into it.' newline ...
newline ...
'\begin{figure}[h] %Make a figure...' newline ...
newline ...
' \includegraphics[trim={0.25in 0 0 0},clip,width=7.5in]{{\\our\server\mypicture}}' newline ...
newline ...
' \captionsetup{labelformat=empty}' newline ...
newline ...
'\end{figure}' newline ...
newline ...
'\end{document}'];
fprintf(fileID,'%s',textext);
fclose(fileID);
% latex dvips ps2pdf
% text.tex -------> text.dvi -------> text.ps --------> text.pdf
[~,cmdoutlatex] = system(['latex.exe -interaction=nonstopmode -output-directory ' exampledir '\ ' texdoc]);
if contains(cmdoutlatex,'Sorry, but latex.exe did not succeed.')
%Do some kind of check and fix things.
end
[~,cmdoutdvips] = system(['dvips.exe -q* -o ' psdoc ' ' dvidoc]);
if contains(cmdoutdvips,'!')
%Do some kind of check and fix things.
error(['Error: ' cmdoutdvips])
end
[~,cmdoutps2pdf] = system(['ps2pdf ' psdoc ' ' pdfdoc ' -sDEVICE=pdfwrite']);
if contains(cmdoutps2pdf,'Error','IgnoreCase',true)
%Do some kind of check and fix things.
error(cmdoutps2pdf)
end
Per #Cris Luengo's suggestion of moving to pdflatex rather than using latex/dvips/ps2pdf commands, this worked. Here is the sample code of what worked for a system command.
[~,pdflatexout] = system(['pdflatex.exe -output-directory ' strrep(exampledir,'\','/') ' ' texdoc]);
%Check for errors.
if contains(pdflatexout,'Sorry, but pdflatex.exe did not succeed.') || ...
contains(pdflatexout,'error','IgnoreCase',true)
%Deliver the error code.
error(pdflatexout)
end
I placed this after fclose(fileID) in the original code and deleted all that had originally come after that line.

how to read from file and display the data in desired rows in Matlab

I am trying to read from a file and display the data in rows 6, 11, 111 and 127 in Matlab. I could not figure out how to do it. I have been searching Matlab forums and this platform for an answer. I used fscanf, textscan and other functions but they did not work as intended. I also used a for loop but again the output was not what I wanted. I can now only read one row and display it. Simply I want to display all of them(data in rows given above) at the same time. How can I do that?
matlab code
n = [0 :1: 127];
%% Problem 1
figure
x1 = cos(0.17*pi*n)
%it creates file and writes content of x1 to the file
fileID = fopen('file.txt','w');
fprintf(fileID,'%d \n',x1);
fclose(fileID);
%line number can be changed in order to obtain wanted values.
fileID = fopen('file.txt');
line = 6;
C = textscan(fileID,'%s',1,'delimiter','\n', 'headerlines',line-1);
celldisp(C)
fclose(fileID);
and this is the file
1
8.607420e-01
4.817537e-01
-3.141076e-02
-5.358268e-01
-8.910065e-01
-9.980267e-01
-8.270806e-01
-4.257793e-01
9.410831e-02
5.877853e-01
9.177546e-01
9.921147e-01
7.901550e-01
3.681246e-01
-1.564345e-01
-6.374240e-01
-9.408808e-01
-9.822873e-01
-7.501111e-01
-3.090170e-01
2.181432e-01
6.845471e-01
9.602937e-01
9.685832e-01
7.071068e-01
2.486899e-01
-2.789911e-01
-7.289686e-01
-9.759168e-01
-9.510565e-01
-6.613119e-01
-1.873813e-01
3.387379e-01
7.705132e-01
9.876883e-01
9.297765e-01
6.129071e-01
1.253332e-01
-3.971479e-01
-8.090170e-01
-9.955620e-01
-9.048271e-01
-5.620834e-01
-6.279052e-02
4.539905e-01
8.443279e-01
9.995066e-01
8.763067e-01
5.090414e-01
-4.288121e-15
-5.090414e-01
-8.763067e-01
-9.995066e-01
-8.443279e-01
-4.539905e-01
6.279052e-02
5.620834e-01
9.048271e-01
9.955620e-01
8.090170e-01
3.971479e-01
-1.253332e-01
-6.129071e-01
-9.297765e-01
-9.876883e-01
-7.705132e-01
-3.387379e-01
1.873813e-01
6.613119e-01
9.510565e-01
9.759168e-01
7.289686e-01
2.789911e-01
-2.486899e-01
-7.071068e-01
-9.685832e-01
-9.602937e-01
-6.845471e-01
-2.181432e-01
3.090170e-01
7.501111e-01
9.822873e-01
9.408808e-01
6.374240e-01
1.564345e-01
-3.681246e-01
-7.901550e-01
-9.921147e-01
-9.177546e-01
-5.877853e-01
-9.410831e-02
4.257793e-01
8.270806e-01
9.980267e-01
8.910065e-01
5.358268e-01
3.141076e-02
-4.817537e-01
-8.607420e-01
-1
-8.607420e-01
-4.817537e-01
3.141076e-02
5.358268e-01
8.910065e-01
9.980267e-01
8.270806e-01
4.257793e-01
-9.410831e-02
-5.877853e-01
-9.177546e-01
-9.921147e-01
-7.901550e-01
-3.681246e-01
1.564345e-01
6.374240e-01
9.408808e-01
9.822873e-01
7.501111e-01
3.090170e-01
-2.181432e-01
-6.845471e-01
-9.602937e-01
-9.685832e-01
-7.071068e-01
-2.486899e-01
2.789911e-01
Assuming the file is not exceedingly large, the simplest way would probably be read the entire file & index the output to your desired lines.
line = [6 11 111 127];
fileID = fopen('file.txt');
C = textscan(fileID,'%s','delimiter','\n');
fclose(fileID);
disp(C{1}(line))

Reading text file in Matlab results in unknown spaces within characters

I am trying to read a text/csv file in Matlab.The file looks like:
VolumeDisplacement,9783.47
CenterOfBuoyancy,-0.732585,3.16072e-14,-3.09939
WettedSurfaceArea,2709.66
WaterlineLength,102.156
MaximumWaterlineBeam,20.76
WaterPlaneArea,1774.4
CenterOfFloatation,-6.32016,1.00108e-11,0
The file is generated using vbscript in Rhinoceros. I am using the standard method given in the help file, but encountering a weird problem.
filename = 'RhinoResult.txt';
fid = fopen(filename);
line = fgetl(fid);
tline = textscan(line,'%s%d','Delimiter',',');
VolumeDisplacement=tline{2};
But, my results are not as expected. The tline is storing the strings with a space between each character. Also, there are two unknown characters (ÿþ) at the beginning.
tline{1} = 'ÿþV o l u m e D i s p l a c e m e n t '
The VBScript used to create the textfile looks like this:
Sub writeResult(arrResults, filePath, fileName)
Dim objFSO,objFile
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile(filePath & fileName, _
ForWriting, True)
objFile.Write "VolumeDisplacement," & arrResults(0)
objFile.Writeline
objFile.Write "CenterOfBuoyancy," & arrResults(1)
objFile.Writeline
objFile.Write "WettedSurfaceArea," & arrResults(2)
objFile.Writeline
objFile.Write "WaterlineLength," & arrResults(3)
objFile.Writeline
objFile.Write "MaximumWaterlineBeam," & arrResults(4)
objFile.Writeline
objFile.Write "WaterPlaneArea," & arrResults(5)
objFile.Writeline
objFile.Write "CenterOfFloatation," & arrResults(6)
objFile.Writeline
objFile.Close
End Sub
Can someone help me with this?
Thanks,
Amitava
If you look at the docs, you'll see
object.CreateTextFile(filename[, overwrite[, unicode]])
Your
Set objFile = objFSO.CreateTextFile(filePath & fileName, _
ForWriting, True)
(probably mis-copied from a .OpenTextFile call) fools .CreateTextFile into using Unicode (evidence: BOM, 'spaces').
So use .CreateTextFile correctly to create (and write to) an ANSI file:
Set objFile = objFSO.CreateTextFile(filePath & fileName, True, False)

Octave: Load all files from specific directory

I used to have Matlab and loaded all txt-files from directory "C:\folder\" into Matlab with the following code:
myFolder = 'C:\folder\';
filepattern = fullfile(myFolder, '*.txt');
files = dir(filepattern);
for i=1:length(files)
eval(['load ' myFolder,files(i).name ' -ascii']);
end
If C:\folder\ contains A.txt, B.txt, C.txt, I would then have matrices A, B and C in the workspace.
The code doesn't work in octave, maybe because of "fullfile"?. Anyway, with the following code I get matrices with the names C__folder_A, C__folder_B, C__folder_C. However, I need matrices called A, B, C.
myFolder = 'C:\folder\';
files = dir(myFolder);
for i=3:length(files)
eval(['load ' myFolder,files(i).name ' -ascii']);
end
Can you help me?
Thanks,
Martin
PS: The loop starts with 3 because files(1).name = . and files(2).name = ..
EDIT:
I have just found a solution. It's not elegant, but it works.
I just add the path in which the files are with "addpath", then I don't have to give the full name of the directory in the loop.
myFolder = 'C:\folder\';
addpath(myFolder)
files = dir(myFolder);
for i=3:length(files)
eval(['load ' files(i).name ' -ascii']);
end
It's usually bad design if you load files to variables which name is generated dynamically and you should load them to a cell array instead but this should work:
files = glob('C:\folder\*.txt')
for i=1:numel(files)
[~, name] = fileparts (files{i});
eval(sprintf('%s = load("%s", "-ascii");', name, files{i}));
endfor
The function scanFiles searches file names with extensions in the current dirrectory (initialPath) and subdirectories recursively. The parameter fileHandler is a function that you can use to process populated file structure (i.e. read text, load image, etc.)
Source
function scanFiles(initialPath, extensions, fileHandler)
persistent total = 0;
persistent depth = 0; depth++;
initialDir = dir(initialPath);
printf('Scanning the directory %s ...\n', initialPath);
for idx = 1 : length(initialDir)
curDir = initialDir(idx);
curPath = strcat(curDir.folder, '\', curDir.name);
if regexp(curDir.name, "(?!(\\.\\.?)).*") * curDir.isdir
scanFiles(curPath, extensions, fileHandler);
elseif regexp(curDir.name, cstrcat("\\.(?i:)(?:", extensions, ")$"))
total++;
file = struct("name",curDir.name,
"path",curPath,
"parent",regexp(curDir.folder,'[^\\\/]*$','match'),
"bytes",curDir.bytes);
fileHandler(file);
endif
end
if!(--depth)
printf('Total number of files:%d\n', total);
total=0;
endif
endfunction
Usage
# txt
# textFileHandlerFunc=#(file)fprintf('%s',fileread(file.path));
# scanFiles("E:\\Examples\\project\\", "txt", textFileHandlerFunc);
# images
# imageFileHandlerFunc=#(file)imread(file.path);
# scanFiles("E:\\Examples\\project\\datasets\\", "jpg|png", imageFileHandlerFunc);
# list files
fileHandlerFunc=#(file)fprintf('path=%s\nname=%s\nsize=%d bytes\nparent=%s\n\n',
file.path,file.name,file.bytes,file.parent);
scanFiles("E:\\Examples\\project\\", "txt", fileHandlerFunc);

Ghostscript error converting multi-page PS to multi-page PDF using pdfwrite

I'm using Matlab to output a multi-page PS file:
print(figure, '-dpsc2', fullfile(folder, [file '.ps']), '-r600', '-append')
and then using Matlab to invoke Ghostscript to convert the resulting PS file to a PDF:
system(['"' gsPath '" -sDEVICE=pdfwrite \
-dDEVICEWIDTHPOINTS=' num2str(int32(width*72)) ' \
-dDEVICEHEIGHTPOINTS=' num2str(int32(height*72)) ' \
-dPDFFitPage \
-o "' fullfile(folder, [file '.pdf']) '" "' fullfile(folder, [file '.ps']) '"']);
which is just a really hard-to-read way of writing something along the lines of
gswin64c -sDEVICE=pdfwrite ^
-dDEVICEWIDTHPOINTS=100 ^
-dDEVICEHEIGHTPOINTS=100 ^
-dPDFFitPage ^
-o "C:\folder\output.pdf" "C:\folder\input.ps"
where I've put in example values for device dimensions and input/output paths. When I use this code to print a single figure (one page) to PDF, everything works perfectly. However, when printing multiple figures (multiple pages) to PDF, Ghostscript throws an error:
GPL Ghostscript 9.06 (2012-08-08)
Copyright (C) 2012 Artifex Software, Inc. All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
**** Unable to open the initial device, quitting.
Now, if I remove the -dDEVICEWIDTHPOINTS=100 -dDEVICEHEIGHTPOINTS=100 part of my Ghostscript command and again attempt to print multiple figures to a PDF, it works fine (except for the page size being different than what I want).
GPL Ghostscript 9.06 (2012-08-08)
Copyright (C) 2012 Artifex Software, Inc. All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
Loading NimbusSanL-Regu font from %rom%Resource/Font/NimbusSanL-Regu... 4032872 2490784 2311720 1014184 2 done.
Has anyone else run into a similar problem and found a workaround for this issue? One of the keys here is that I need to be able to control the page size of the PDF produced. Thanks!
Below is an example that should run fine. First we create a multi-page PS file:
fname = 'test';
if exist([fname '.ps'], 'file'), delete([fname '.ps']); end
hfig = figure;
for i=1:10
plot(cumsum(rand(100,1)-0.5))
drawnow
print(hfig, '-dpsc2', '-append', [fname '.ps'])
end
close(hfig)
Next we convert it to PDF using Ghostscript, and properly crop the figures:
gs_path = 'C:\Program Files\gs\gs9.07\bin\gswin64c.exe';
gs_opts = '-dBATCH -dNOPAUSE -q';
% ps2pdf
cmd = sprintf('"%s" %s -sDEVICE=pdfwrite -dPDFFitPage -o %s %s', ...
gs_path, gs_opts, [fname '.pdf'], [fname '.ps']);
disp(cmd); system(cmd);
% get bbox
cmd = sprintf('"%s" %s -sDEVICE=bbox %s', ...
gs_path, gs_opts, [fname '.pdf']);
disp(cmd); [~,out] = system(cmd);
out = textscan(out, '%s', 'Delimiter','');
bbox = regexp(out{1}, '^%%BoundingBox: (\d+) (\d+) (\d+) (\d+)','tokens','once');
bbox = str2double(vertcat(bbox{:}));
bbox = [min(bbox(:,1:2)) max(bbox(:,3:4))];
% crop to bounding box
cmd = sprintf(['"%s" %s -o %s -sDEVICE=pdfwrite' ...
' -dDEVICEWIDTHPOINTS=%d -dDEVICEHEIGHTPOINTS=%d -dFIXEDMEDIA' ...
' -c "<</PageOffset [-%d -%d]>> setpagedevice" -f %s'], ...
gs_path, gs_opts, [fname '_cropped.pdf'], ...
bbox(3)-bbox(1), bbox(4)-bbox(2), bbox(1), bbox(2), [fname '.pdf']);
disp(cmd); system(cmd);