I have a matrix defined so if I do this
(format t "~a" (get-real-2d 0 0))
it prints out the element in the first row first column
and if I do this
(format t "~a" (get-real-2d a 0 1))
it prints out the element in first row second column
and if I do this
(format t "~a" (get-real-2d a 1 0))
it prints out the element in second row first column.
The matrix a looks like this
a =
((0 1 2)
(3 4 5)
(6 7 8))
and I was hoping you can show me exactly how to write a dotimes loop or other loop
that would in as few lines as possible would print out the matrix using the get-real-2d function so the output looks like this:
0 1 2
3 4 5
6 7 8
I'm just hoping you can show me a slick loop that would be real small that I can use to print matrices that I can use in my lisp library something real professional looking, like one that would use only variables. Something like:
(format t "~a" (get-real-2d i j))
instead of a bunch of:
(format t "~a" (get-real-2d 0 0))
(format t "~a" (get-real-2d 0 1))
(format t "~a" (get-real-2d 0 2))
;;;;LATEST EDIT;;;
to make this simple I call
(defparameter a (create-mat 3 3 +32fc1+))
to create a 3x3 matrix - create-mat is a wrapper for opencv's cvCreateMat
the output from that command at repl is
(defparameter a (create-mat 3 3 +32fc1+))
A
CL-OPENCV> a
#.(SB-SYS:INT-SAP #X7FFFD8000E00)
i/e the variable a is a pointer to the 3x3 matrix
then I run
(defparameter data (cffi:foreign-alloc :float :initial-contents
'(0.0f0 1.0f0 2.0f0 3.0f0 4.0f0 5.0f0 6.0f0 7.0f0 8.0f0)))
to create the data for the matrix - which I next will allocate to the matrix
the output from that command at repl is
CL-OPENCV> (defparameter data (cffi:foreign-alloc :float :initial-contents
'(0.0f0 1.0f0 2.0f0 3.0f0 4.0f0 5.0f0 6.0f0 7.0f0 8.0f0)))
DATA
CL-OPENCV> data
#.(SB-SYS:INT-SAP #X7FFFD8000E40)
i/e the variable a is data pointer to the data ill add to the matrix
then I call..
(set-data a data 12) to add the data to the matrix - set-data is a wrapper for opencv's cvSetData
so now when I run - (get-real-2d is a wrapper for opencv's cvGetReal2d)
(get-real-2d a 0 0) it gets the element of matrix a at row 0 col 0 which is 0.0d0
the output from that command at repl is
CL-OPENCV> (get-real-2d a 0 0)
0.0d0
and now when I run
(get-real-2d a 0 1) it gets the element of matrix a at row 0 col 1 which is is 0.0d0
the output from that command at repl is
CL-OPENCV> (get-real-2d a 0 1)
1.0d0
and when I run this loop
(dotimes (i 3)
(dotimes (j 3)
(format t "~a~%" (get-real-2d a i j))))
the output from that command at repl is
CL-OPENCV> (dotimes (i 3)
(dotimes (j 3)
(format t "~a~%" (get-real-2d a i j))))
0.0d0
1.0d0
2.0d0
3.0d0
4.0d0
5.0d0
6.0d0
7.0d0
8.0d0
NIL
but when I try your method #Svante
(dotimes (i 3)
(dotimes (j 3)
(format t "~{~{~a~^ ~}~%~}" (get-real-2d a i j))))
I get error:
The value 0.0d0 is not of type LIST.
[Condition of type TYPE-ERROR]
because the output of 1 run of get-real-2d is just a 1 number float i/e
CL-OPENCV> (get-real-2d a 0 0)
0.0d0
with that info can you help me print the matrix so it looks like this
0.0d0 1.0d0 2.0d0
3.0d0 4.0d0 5.0d0
6.0d0 7.0d0 8.0d0
You can do that directly in the format directive. The format instructions ~{ and ~} descend into a list structure.
(format t "~{~{~a~^ ~}~%~}" matrix)
The outer pair of ~{ ~} loops over the first level of the matrix, so that the directives inside get to see one row at a time. The inner pair of ~{ ~} loops over each such row, so that the directives inside get to see one element at a time. ~A prints that element. The part between ~^ and ~} gets printed only between executions of the loop body, not at the end. ~% emits a #\Newline.
EDIT as requested
Note that the ~{ ~} replace the looping, and that I named the variable matrix, not element. You need to put the entire matrix there, and it is supposed to be in the form of a nested list. I deduced this from your statement that a is ((0 1 2) (3 4 5) (6 7 8)). So, (format t "~{~{~a~^ ~}~%~}" a).
If the matrix happens not to be in the form of a nested list but rather some kind of array, you really need to loop over the indices. Nested dotimes forms should be sufficient at first:
(fresh-line)
(dotimes (i (array-dimension array 0))
(dotimes (j (array-dimension array 1))
(format t "~a " (aref array i j)))
(terpri))
I don't know how your matrices map to arrays, so you will have to replace array-dimension and aref with your versions.
Your question can be understood in two ways, and that is why it has two solutions:
Define method for printing object of type matrix (in this case it may use the knowledge about the internal structure of matrix):
(defmethod print-object ((matrix matrix) stream)
(format stream "~{~{~a~^ ~}~%~}" matrix))
Using format as is shown in the answers.
Define client function that can use the only method of your object - get-real-2d:
(defun print-matrix (matrix dimension-x dimension-y)
(dotimes (x dimension-x)
(dotimes (y dimension-y)
(princ (get-real-2d matrix x y))
(princ #\Space))
(princ #\Newline)))
Just using dotimes.
Here are just the two dotimes loops that you were asking for. The only thing that you need to pay attention for is when to print spaces and when to print newlines.
(dotimes (i 3)
(dotimes (j 3)
(princ (get-real-2d a i j))
(if (< j 2)
(princ #\Space)
(terpri))))
Alternatively, you might want to use the format directives for floating point printing to have the numbers always aligned in nice columns. You can choose between ~F that will never print an exponent, ~E that will always print one, and ~G that behaves according to the magnitude. Look for details here in the HyperSpec: http://www.lispworks.com/documentation/HyperSpec/Body/22_cc.htm.
Here's an example that uses ~F with a maximum field width of 5 and 1 fractional digit:
(dotimes (i 3)
(dotimes (j 3)
(format t "~5,1F" (get-real-2d a i j)))
(terpri))
This isn't hard, so I'd rather leave it to you to figure out, but here are some tips to make a "slick loop" Lisp-style. I would suggest one or more instances of mapc (or mapcar), rather than dotimes. This may feel odd if you're not used to functional programming, but once you're used to it, it's easier to read than dotimes, and you don't have to keep track of the indexes, so it can avoid errors. You really should learn to use mapcar/mapc if you aren't already familiar with them. They are cool. Or if you want to be really cool :-) you could use recursion to iterate over the matrix, but I think that for this purpose iterating using mapc will be easier to read. (But you should learn the recursive way for other jobs. If you find recursion confusing--I have no reason to think you do, but some people have trouble with it--my favorite tutorial is The Little Schemer.)
You may also want to use other format directives that allow you pad numbers with spaces if they don't have enough digits. The ~% directive may be useful as well. Peter Seibel has a very nice introduction to format.
Related
I recently posted on here to get help with a formula, here is the link...https://stackoverflow.com/questions/75068029/vlook-up-style-forumla-but-range-is-2-cells A user called rockinfreakshow was really awesome and provided a great solution for me. I'm not very experienced and don't understand what the formula at all but I'd love to be able to add more attributes to it. Is anyone able to help break it down for me ?
I havent tried anything here, it's totally out of my realm of understanding
=MAKEARRAY(COUNTA(B2:B),COUNTA(D1:O1),LAMBDA(r,c,IF(REGEXMATCH(LAMBDA(ax,bx,IFS(REGEXMATCH(ax,"Mixed")*REGEXMATCH(INDEX(C2:C,r),"Blend")*REGEXMATCH(INDEX(C2:C,r),"Filter"),"BLEND-"&bx&"|FILTER-"&bx,REGEXMATCH(ax,"Mixed")*NOT(REGEXMATCH(INDEX(C2:C,r),"Blend"))*REGEXMATCH(INDEX(C2:C,r),"Filter"),"ESP-"&bx&"|FILTER-"&bx,REGEXMATCH(ax,"Mixed")*NOT(REGEXMATCH(INDEX(C2:C,r),"Filter")),"BLEND-"&bx&"|ESP-"&bx,LEN(ax),SUBSTITUTE(ax&"-"&bx,"Espresso","ESP")))(regexextract(INDEX(B2:B,r),"([^\s]*?) Subscription"),IFNA(SWITCH(REGEXEXTRACT(INDEX(C2:C,r),"Small|Medium|Large"),"Small",250,"Medium",450,"Large",900),SWITCH(REGEXEXTRACT(INDEX(B2:B,r),"Medium|Large"),"Medium",225,"Large",450))),"(?i)"&INDEX(D1:O1,,c)),1,)))
see the WHY LAMBDA? part of this answer to understand the LAMBDA
the formula contains 2x LAMBDA and there are a total of 4 placeholders which translates to:
r - COUNTA(B2:B)
c - COUNTA(D1:O1)
ax - REGEXEXTRACT(INDEX(B2:B, r), "([^\s]*?) Subscription")
bx - IFNA(SWITCH(REGEXEXTRACT(INDEX(C2:C, r), "Small|Medium|Large"),
"Small", 250, "Medium", 450, "Large", 900),
SWITCH(REGEXEXTRACT(INDEX(B2:B, r), "Medium|Large"),
"Medium", 225, "Large", 450))
r counts how many items are in B column
c counts how many items are in row 1 of range D1:O1
ax extracts the word from B column that precedes the word Subscription
bx is a bit complex but essentially it extracts from C column word Small or Medium or Large and replaces it with 250, 450 or 900 respectively. then if C column does not contain one of those 3 words it checks for Medium or Large within B column and assigns 225 or 450 respectively
what we are left with is the core of the formula:
IFS( REGEXMATCH(ax, "Mixed")*
REGEXMATCH(INDEX(C2:C, r), "Blend")*
REGEXMATCH(INDEX(C2:C, r), "Filter"), "BLEND-"&bx&"|FILTER-"&bx,
___________________________________________________________________________
REGEXMATCH(ax, "Mixed")*
NOT(REGEXMATCH(INDEX(C2:C, r), "Blend"))*
REGEXMATCH(INDEX(C2:C, r), "Filter"), "ESP-"&bx&"|FILTER-"&bx,
___________________________________________________________________________
REGEXMATCH(ax, "Mixed")*
NOT(REGEXMATCH(INDEX(C2:C, r), "Filter")), "BLEND-"&bx&"|ESP-"&bx,
___________________________________________________________________________
LEN(ax), SUBSTITUTE(ax&"-"&bx, "Espresso", "ESP"))
for better visualization, the IFS formula contains only 4 elements. each of these 4 elements acts as a switch - if there is a match x we get output y. for example let's dissect the first element...
REGEXMATCH(ax, "Mixed")*
REGEXMATCH(INDEX(C2:C, r), "Blend")*
REGEXMATCH(INDEX(C2:C, r), "Filter"), "BLEND-"&bx&"|FILTER-"&bx
there are 3x REGEXMATCHes multiplied by each other. whenever there is such multiplication in array formulae it translates as AND logic gate (if there would be + it would mean OR logic gate) eg.:
1 * 1 = 1
1 * 0 = 0
0 * 1 = 0
0 * 0 = 0
REGEXMATCH outputs TRUE or FALSE so if we get 3x TRUE the whole argument is considered as TRUE (because 1 * 1 * 1 = 1) so we proceed to output our first switch
therefore if B column contains Mixed and C column contains Blend and C column contains Filter then we output Blend-000|Filter-000 where 000 stands for a specific number determined from bx placeholder/formula and also you can notice the | (which btw stands for OR logic within the regex) but in this case, it's just a unique symbol to join stuff for REGEXMATCH. which REGEXMATCH is this for you may ask? ...this one:
so the output of IFS formula is the input for most outer REGEXMATCH and we check if the IFS output matches something within D1:O1 range. IF yes then output 1 otherwise output nothing. shortened:
IF(REGEXMATCH(IFS(...), "(?i)"&INDEX(D1:O1,,c), 1, )
(?i) in regex means "case insensitive". it is there just for safety reasons because regex is by default case sensitive.
and we reached the MAKEARRAY formula that creates an array of numbers across the whole range with height r and width c where output is the result of IF eg. either 1 or empty cell
If I create several empty labels on an Audacity 2.4.2 audio track (by clicking at various points along the track, and pressing Ctrl-B after each click), the Nyquist Prompt evaluates the expression
(cadar (aud-get-info "Labels"))
...to a list L whose elements are, in turn, 3-element sublists.
For the sake of this description, I will refer to these 3-element sublists as "triples".
As it happens, for each of these triples, the first two elements are identical floating point numbers, and last element is the empty string.
Thus, a typical instance of such a list L may begin with something like
((0.12345 0.12345 "") (6.78901 6.78901 "") (23.45678 23.45678 "") ...
How can I create a new list consisting of all the first elements of such a list L?
For example, if my initial list L begins as shown above, what Nyquist expression involving the list L will evaluate to a list beginning as shown below?
(0.12345 6.78901 23.45678 ...)
(I tried stuff like (mapc (lambda (x) x) (cadar (aud-get-info "Labels"))), which not only failed to produce the desired result, but in some cases actually caused the addition of several new labels to the track, something I find completely bewildering. Therefore, as strange as this may sound, I must stress that I am looking for solutions that leave the original interface unchanged, and, in particular, do not add any new labels the currently selected track.)
I'm using the current Audacity 3.1.3 version, but this should all be the same for Audacity 2.4.2.
In the Nyquist Prompt, if you run with the Debug button:
(print (aud-get-info "Labels"))
You will see an output similar to:
((1 ((0.184322 0.184322 "") (0.654661 1.24576 "") (2.25424 2.25424 ""))))
The first "1" is the track number (zero indexed).
If there are two label tracks, it will look something like:
((1 ((0.184322 0.184322 "") (0.654661 1.24576 "") (2.25424 2.25424 "")))
(3 ((0.449153 0.449153 ""))))
Each label is in the form:
(start-time end-time "Label text")
(Observe that the second label in track 1 is a region label.)
Thus the format of the data returned by (aud-get-info "Labels") is in the form:
(list (list track-num (list (first-label) (second-label) ...))
(list track-num (list (first-label) ...)))
To get a list of labels from each track:
(let ((label-info (aud-get-info "Labels")))
(dolist (track label-info)
(print (second track))))
which, in the above case, will print to the Debug window:
((0.184322 0.184322 "") (0.654661 1.24576 "") (2.25424 2.25424 ""))
((0.449153 0.449153 ""))
To create a list of each label start times:
(let ((output-list ())
(label-info (aud-get-info "Labels")))
(dolist (track label-info) ;step through each track in label-info
(setf labels (second track))
(dolist (label labels) ;step through each label in labels
(setf start-time (first label))
(push start-time output-list)))
;; Print the list:
(format nil "~a" output-list))
Which, in the above example. prints:
(0.449153 2.25424 0.654661 0.184322)
Given a value x and an integer n (assigned at runtime), I want to print x to exactly n digits after the decimal (after rounding if needed).
print(round(x, n)) works fine for (x,n)=(3.141592, 3) but for (x,n)=(2.5,5), it prints just 2.5, not 2.50000 (5 digits after decimal point).
If I knew n at runtime, say 5, I could do
#printf("%.5f", x)
But #printf being a macro needs n to be known at compile time.
Is this possible using some show magic or something else?
Using the fresh new Format.jl package:
using Format
function foo(x, n)
f = FormatSpec(".$(n)f")
pyfmt(f, x)
end
foo(2.5, 5)
Unfortunately, for some reason the julia version of #printf / #sprintf do not support the "width" sub-specifier as per the c printf standard (see man 3 printf).
If you're feeling brave, you can rely on the c sprintf which supports the "dynamic width" modifier, to collect a string that you then just print as normal.
A = Vector{UInt8}(100); # initialise array of 100 "chars"
ccall( :sprintf, Int32, (Ptr{UInt8}, Cstring, Int64, Float64), A, "%.*f", 4, 0.1 )
print( unsafe_string(pointer(A)) ) #> 0.1000
Note the asterisk in %.*f, and the extra input 4 serving as the dynamic width modifier.
So i basically want to printbst's .. here is a little more detail
Provide a function (printbst t) that prints a BST constructed from BST as provided by bst.rkt in the following format:
-Each node in the BST should be printed on a separate line;
-the left subtree should be printed after the root;
-The right subtree should be printed before the root;
-The key value should be indented by 2d spaces where d is its depth, or distance from the root. That is, the root should not be indented, the keys in its subtrees should be intended 2 spaces, the keys in their subtrees 4 spaces, and so on.
For example, the complete tree containing {1,2,3,4,5,6} would be printed like this:
6
5
4
3
2
1
Observe that if you rotate the output clockwise and connect each node to its subtrees, you arrive at the conventional graphical representation of the tree. Do not use mutation.
Here is what i have so far:
#lang racket
;;Note: struct-out exports all functions associated with the structure
(provide (struct-out BST))
(define-struct BST (key left right) #:transparent)
(define (depth key bst)
(cond
[(or (empty? bst) (= key (BST-key bst))) 0]
[else (+ 1 (depth key (BST-right bst)) (depth key (BST-left bst)))]))
(define (indent int)
(cond
[(= int 0) ""]
[else " " (indent (sub1 int))]))
(define (printbst t)
(cond
[(empty? t) (newline)]
[(and (empty? (BST-right t)) (empty? (BST-left t)))
(printf "~a~a" (indent (depth (BST-key t) t)) (BST-key t))]))
My printbst only prints a tree with one node thou .... i have an idea but it involves mutation, which i can't use :( ..... Any suggestions ? Should i change my approach to the problem all together?
Short answer: yes, you're going to want to restructure this more or less completely.
On the bright side, I like your indent function :)
The easiest way to write this problem involves making recursive calls on the subtrees. I hope I'm not giving away too much when I tell you that in order to print a subtree, there's one extra piece of information that you need.
...
Based on our discussion below, I'm going to first suggest that you develop the closely related recursive program that prints out the desired numbers with no indentation. So then the correct output would be:
6
5
4
3
2
1
Updating that program to the one that handles indentation is just a question of passing along a single extra piece of information.
P.S.: questions like this that produce output are almost impossible to write good test cases for, and consequently not great for homework. I hope for your sake that you have lots of other problems that don't involve output....
Here's the brief problem:
Input: a list of strings, each containing numbers
(" 3.4 5.4 1.2 6.4" "7.8 5.6 4.3" "1.2 3.2 5.4")
Output: a list of numbers
(3.4 5.4 1.2 6.4 7.8 5.6 4.3 1.2 3.2 5.4)
Here's my attempt at coding this:
(defun parse-string-to-float (line &optional (start 0))
"Parses a list of floats out of a given string"
(if (equalp "" line)
nil
(let ((num (multiple-value-list (read-from-string (subseq line start)))))
(if (null (first num))
nil
(cons (first num) (parse-string-to-float (subseq line (+ start (second num)))))))))
(defvar *data* (list " 3.4 5.4 1.2 6.4" "7.8 5.6 4.3" "1.2 3.2 5.4"))
(setf *data* (format nil "~{~a ~}" *data*))
(print (parse-string-to-float *data*))
===> (3.4 5.4 1.2 6.4 7.8 5.6 4.3 1.2 3.2 5.4)
However, for rather large data sets, it's a slow process. I'm guessing the recursion isn't as tight as possible and I'm doing something unnecessary. Any ideas?
Furthermore, the grand project involves taking an input file that has various data sections separated by keywords. Example -
%FLAG START_COORDS
1 2 5 8 10 12
%FLAG END_COORDS
3 7 3 23 9 26
%FLAG NAMES
ct re ct cg kl ct
etc...
I'm trying to parse a hash-table with the keywords that follow %FLAG as the keys, and the values stored as number or string lists depending on the particular keyword I'm parsing. Any ideas for libraries that already do this very type of job, or simple ways around this in lisp?
This is not a task you want to be doing recursively to begin with. Instead, use LOOP and a COLLECT clause. For example:
(defun parse-string-to-floats (line)
(loop
:with n := (length line)
:for pos := 0 :then chars
:while (< pos n)
:for (float chars) := (multiple-value-list
(read-from-string line nil nil :start pos))
:collect float))
Also, you might want to consider using WITH-INPUT-FROM-STRING instead of READ-FROM-STRING, which makes things even simpler.
(defun parse-string-to-float (line)
(with-input-from-string (s line)
(loop
:for num := (read s nil nil)
:while num
:collect num)))
As for performance, you might want to do some profiling, and ensure that you are actually compiling your function.
EDIT to add: One thing you do need to be careful of is that the reader can introduce a security hole if you're not sure of the source of the string. There's a read macro, #., which can allow evaluation of arbitrary code following it when it's read from a string. The best way to protect yourself is by binding the *READ-EVAL* variable to NIL, which will make the reader signal an error if it encounters #.. Alternatively, you can use one of the specialized libraries that Rainer Joswig mentions in his answer.
Parse a single string:
(defun parse-string-to-floats (string)
(let ((*read-eval* nil))
(with-input-from-string (stream string)
(loop for number = (read stream nil nil)
while number collect number))))
Process a list of strings and return a single list:
(defun parse-list-of-strings (list)
(mapcan #'parse-string-to-floats list))
Example:
CL-USER 114 > (parse-list-of-strings (list "1.1 2.3 4.5" "1.17 2.6 7.3"))
(1.1 2.3 4.5 1.17 2.6 7.3)
Note:
A costly operation is READ to read float values from streams. There are libraries like PARSE-NUMBER that might be more efficient - some Common Lisp implementation also might have the equivalent of a READ-FLOAT / PARSE-FLOAT function.
Also for performance, try
(declare (optimize (speed 3)))
inside your defun. Some lisps (for example SBCL) will print helpful messages about where it could not optimize, and the estimated cost of not having this optimization
As for performance, try at least measuring the memory allocation. I guess that all the performance is eaten by memory allocation and GC: you allocate a lot of big strings with subseq. E.g., (time (parse-string-to-float ..)) will show you how much time is spent in your code, how much in GC and how much memory was allocated.
If this is the case, then use string-stream (like in with-input-from-string) to decrease GC pressure.