including internally created strings in octave system/unix command? - octave

I have a script like:
#!/opt/bin/octave -qf
xin = dlmread(argv(){1},",");
tim = dlmread("Time");
fileout = [argv(){1} "-" "avg"];
## calcs to create xtemp and time matrices
dlmwrite("Time-avg",time);
dlmwrite(fileout,xtemp,",");
## ?? unix("paste -d',' Time-avg fileout > DATCOARSE");
This all works fine until the last line. I create fileout inside the script to correlate with the input datafile, and fileout prints out fine.
Is there some kind of dereferencing operator in octave to use "fileout" in the unix or system command?

You can use sprintf to create the command string:
cmd_str = sprintf ("paste -d',' Time-avg %s > DATCOARSE", fileout);
unix (cmd_str)
But you don't have to use "paste" at all. You can just concatenate the matrices in octave
dlmwrite ("DATCOARSE", [time, xtemp], ",");

Related

How to get the environment decimal separator in Octave

I need to assign to a variable the environment decimal separator in Octave.
For example, if the pc is set in US format
>> decsep
ans = .
Instead if you run the script from a pc that has European decimal format the output will be
>> decsep
ans = ,
You can use Java to get the decimal separator:
Format = javaMethod( "getInstance", "java.text.DecimalFormat" );
Symbols = javaMethod( "getDecimalFormatSymbols", Format );
Sep = javaMethod( "getDecimalSeparator", Symbols )
Alternatively you can use the following PowerShell (powershell.exe or pwsh.exe) script:
[~, s] = system("pwsh -command (Get-Culture).NumberFormat.NumberDecimalSeparator");
Sep = s(1);
On Linux, you can use:
[~, s] = system('locale decimal_point'); %returns decimal separator and a '↵'
decsp = s(1); %Required answer

Gnuplot Function

How can I plot a function with x being a value from my datafile? Something like that:
set encoding utf8
set term postscript eps enhanced color font "Helvetica, 20"
set output 'kernel.eps'
# Mean & Standard Deviation
load "mean_sd.dat"
# Bandwidth
h = 1.6*sd*n**(-0.2)
# Kernel Function
K(x) = exp(-x*x/2.0)/(sqrt(2.0*pi))
# PLOT --> THIS DOES NOT WORK
# EACH VALUE IN $2 MUST BE USED FOR A SINGLE K(X)
plot for [i=1:n] 'probability.dat' using 0:(K((x - $2)/h))
My data file 'probability.dat':
366.000000 3.153012
366.000000 4.211409
366.000000 3.845248
366.000000 4.131654
366.000000 3.956508
Thank you in advance.
I am not sure that I understood your question correctly, but if you want to plot the kernel function for all values from the second column, then one could proceed for example as follows:
set encoding utf8
set term postscript eps enhanced color font "Helvetica, 20"
set output 'kernel.eps'
# Mean & Standard Deviation
sd=1
n=1
# Bandwidth
h = 1.6*sd*n**(-0.2)
# Kernel Function
K(x) = exp(-x*x/2.0)/(sqrt(2.0*pi))
# PLOT --> THIS DOES NOT WORK
# EACH VALUE IN $2 MUST BE USED FOR A SINGLE K(X)
fname = 'probability.txt'
N = system(sprintf("wc -l %s | gawk '{print $1}'", fname))
cmd(i) = system(sprintf("gawk 'NR==%d{print $2;exit}' %s", i, fname))
set key left top reverse
set xr [-10:10]
plot for [i=1:N] K((x - cmd(i))/h) title sprintf("%.3f", real(cmd(i))) lw 2
Here, the "strategy" is to:
find the total number or records in the input file with (alternatively, one could use the stats command)
N = system(sprintf("wc -l %s | gawk '{print $1}'", fname))
define a function which extracts the ith value from the input file
cmd(i) = sprintf("gawk 'NR==%d{print $2;exit}' %s", i, fname)
The output is then:

octave/matlab read text file line by line and save only numbers into matrix

I have a question regarding octave or matlab data post processing.
I have files exported from fluent like below:
"Surface Integral Report"
Mass-Weighted Average
Static Temperature (k)
crossplane-x-0.001 1242.9402
crossplane-x-0.025 1243.0017
crossplane-x-0.050 1243.2036
crossplane-x-0.075 1243.5321
crossplane-x-0.100 1243.9176
And I want to use octave/matlab for post processing.
If I read first line by line, and save only the lines with "crossplane-x-" into a new file, or directly save the data in those lines into a matrix. Since I have many similar files, I can make plots by just calling their titles.
But I go trouble on identify lines which contain the char "crossplane-x-". I am trying to do things like this:
clear, clean, clc;
% open a file and read line by line
fid = fopen ("h20H22_alongHGpath_temp.dat");
% save full lines into a new file if only chars inside
txtread = fgetl (fid)
num_of_lines = fskipl(fid, Inf);
char = 'crossplane-x-'
for i=1:num_of_lines,
if char in fgetl(fid)
[x, nx] = fscanf(fid);
print x
endif
endfor
fclose (fid);
Would anybody shed some light on this issue ? Am I using the right function ? Thank you.
Here's a quick way for your specific file:
>> S = fileread("myfile.dat"); % collect file contents into string
>> C = strsplit(S, "crossplane-x-"); % first cell is the header, rest is data
>> M = str2num (strcat (C{2:end})) % concatenate datastrings, convert to numbers
M =
1.0000e-03 1.2429e+03
2.5000e-02 1.2430e+03
5.0000e-02 1.2432e+03
7.5000e-02 1.2435e+03
1.0000e-01 1.2439e+03

vimscript: commands that work in mappings, but not in functions

How can I rewrite these 2 commands, which work fine in a mapping, so that they will work in a function?
:if has_key(glos,#g)==1<cr>:let #j=eval('glos.'.#g)<cr>
The function concerned is executed by vim without comment, but #j remains unchanged, as if they had failed, but no message/error is generated.
Here is the complete code involved, the command that loads the dictionary, the function that does not work, and the mapping from that function that does.
" read the glossary into the dictionary, glos
let glos=eval(join(readfile("glossary.dict")))
" 2click item of interest and this will
" send image filepath to xv
" if item all-caps find same at start of its line
" If capitalized at eol find same at start of its line
" if all lower-case at eol find next occurrence of same
" look lower-case or capitalized word up in glossary.txt
" find _\d\+ (page no.) alone on its line in text
com! F call F()
function! F()
normal "ayiw"cyE"by$
let #c=substitute(#c,"[,.?':;!]\+","","g")
if #c=~'images\/ss\d\d\d*'
let #i='!display -geometry +0+0 '.#c.' &'
pkill display
#i
elseif #c==toupper(#c)
let #n=search('^'.#c,'sw')
elseif #c!=#b
let #f=3
let #g=tolower(#c)
while #f>0
try
let #j=eval('glos.'.#g)
catch
let #f=#f-1
let #g=strpart(#g,0,strlen(#g)-1)
continue
endtry
break
endwh
if #f>0
let #h=substitute(#j," glosimgs.*",'','')
if #h!=#j
let #i='!xv -geometry +0+380 '.substitute(#j,'^.\{-}\( glosimgs.*\)$','\1','').' &'
!pkill xv
#i
endif
echo #h
else
echo 'No matching entry for '.#c
endif
elseif #c=~'\u\l\+$'
let #n=search('^'.#c,'sw')
elseif #c=~'\l\+$'
norm *
elseif #c=~'^_\w\+$'
let #/='^'.#c.'$'
norm nzz
endif
endfunction
map <silent> <2-LeftMouse> "ayiw"cyE"by$:let #c=substitute(#c,"[,.?':;!]\+","","g")<cr>:if #c=~'images\/ss\d\d\d*'<cr>:let #i='!display -geometry +0+0 '.#c.' &'<cr>:pkill display<cr>:#i<cr>:elseif #c==toupper(#c)<cr>:let #n=search('^'.#c,'sw')<cr>:elseif #c!=#b<cr>:let #f=3<cr>:let #g=tolower(#c)<cr>:while #f>0<cr>:try<cr>:let #j=eval('glos["'.#g.'"]')<cr>:catch<cr>:let #f=#f-1<cr>:let #g=strpart(#g,0,strlen(#g)-1)<cr>:continue<cr>:endtry<cr>:break<cr>:endwh<cr>:if #f>0<cr>:let #h=substitute(#j," glosimgs.*",'','')<cr>:if #h!=#j<cr>:let #i='!xv -geometry +0+380 '.substitute(#j,'^.\{-}\( glosimgs.*\)$','\1','').' &'<cr>:!pkill xv<cr>:#i<cr>:endif<cr><cr<cr>>:echo #h<cr>:else<cr>:echo 'No matching entry for '.#c<cr>:endif<cr>:elseif #c=~'\u\l\+$'<cr>:let #n=search('^'.#c,'sw')<cr>:elseif #c=~'\l\+$'<cr>:norm *<cr>:elseif #c=~'^_\w\+$'<cr>:let #/='^'.#c.'$'<cr>:norm nzz<cr>:endif<cr>
Specifically, I should have written:
:if has_key(**g:**glos,#g)==1:let #j=eval('**g:**glos.'.#g)
:h g: goes straight to the heart of the matter; in a function all references are local to that function, so references to any variable outside the function must be global, by prepending 'g:' to the variable name. As I created the dictionary independent of the function, the function must reference it as a global item.
Of course, if you are not aware of 'g:', it is rather difficult to find that help reference, but that's a frequent problem using help.
And, of course, the ** surrounding g: aren't required, that's what this site gives you in lieu of bolded text, apparently.

Read An Input.md file and output a .html file Haskell

I had a question concerning some basic transformations in Haskell.
Basically, I have a written Input file, named Input.md. This contains some markdown text that is read in my project file, and I want to write a few functions to do transformations on the text. After completing these functions under a function called convertToHTML, I have output the file as an .html file in the correct format.
module Main
(
convertToHTML,
main
) where
import System.Environment (getArgs)
import System.IO
import Data.Char (toLower, toUpper)
process :: String -> String
process s = head $ lines s
convertToHTML :: String -> String
convertToHTML str = do
x <- str
if (x == '#')
then "<h1>"
else return x
--convertToHTML x = map toUpper x
main = do
args <- getArgs -- command line args
let (infile,outfile) = (\(x:y:ys)->(x,y)) args
putStrLn $ "Input file: " ++ infile
putStrLn $ "Output file: " ++ outfile
contents <- readFile infile
writeFile outfile $ convertToHTML contents
So,
How would I read through my input file, and transform any line that starts with a # to an html tag
How would I read through my input file once more and transform any WORD that is surrounded by _word_ (1 underscore) to another html tag
Replace any Character with an html string.
I tried using such functions such as Map, Filter, ZipWith, but could not figure out how to iterate through the text and transform each text. Please if anybody has any suggestions. I've been working on this for 2 days straight and have a bunch of failed code to show for a couple of weeks and have a bunch of failed code to show it.
I tried using such functions such as Map, Filter, ZipWith, but could not figure out how to iterate through the text and transform each text.
Because they work on appropriate element collection. And they don't really "iterate"; you simply have to feed the appropriate data. Let's tackle the # problem as an example.
Our file is one giant String, and what we'd like is to have it nicely split in lines, so [String]. What could do it for us? I have no idea, so let's just search Hoogle for String -> [String].
Ah, there we go, lines function! Its counterpart, unlines, is also going to be useful. Now we can write our line wrapper:
convertHeader :: String -> String
convertHeader [] = [] -- that prevents us from calling head on an empty line
convertHeader x = if head x == '#' then "<h1>" ++ x ++ "</h1>"
else x
and so:
convertHeaders :: String -> String
convertHeaders = unlines . map convertHeader . lines
-- ^String ^[String] ^[String] ^String
As you can see the function first converts the file to lines, maps convertHeader on each line, and the puts the file back together.
See it live on Ideone
Try now doing the same with words to replace your formatting patterns. As a bonus exercise, change convertHeader to count the number of # in front of the line and output <h1>, <h2>, <h3> and so on accordingly.