HowTo: select all rows in a cell array, where a particular column has a particular value - octave

I have a cell array, A. I would like to select all rows where the first column (for example) has the value 1234 (for example).
When A is not a cell array, I can accomplish this by:
B = A(A(:,1) == 1234,:);
But when A is a cell array, I get this error message:
error: binary operator `==' not implemented for `cell' by `scalar' operations
Does anyone know how to accomplish this, for a cell array?

The problem is the expression a(:,1) == 1234 (and also a{:,1} == 1234).
For example:
octave-3.4.0:48> a
a =
{
[1,1] = 10
[2,1] = 13
[3,1] = 15
[4,1] = 13
[1,2] = foo
[2,2] = 19
[3,2] = bar
[4,2] = 999
}
octave-3.4.0:49> a(:,1) == 13
error: binary operator `==' not implemented for `cell' by `scalar' operations
octave-3.4.0:49> a{:,1} == 13
error: binary operator `==' not implemented for `cs-list' by `scalar' operations
I don't know if this is the simplest or most efficient way to do it, but this works:
octave-3.4.0:49> cellfun(#(x) isequal(x, 13), a(:,1))
ans =
0
1
0
1
octave-3.4.0:50> a(cellfun(#(x) isequal(x, 13), a(:,1)), :)
ans =
{
[1,1] = 13
[2,1] = 13
[1,2] = 19
[2,2] = 999
}

I guess the Class of A is cell. (You can see in the Workspace box).
So you may need to convert A to the matrix by cell2mat(A).
Then, just like Matlab as you did: B = A(A(:,1) == 1234,:);

I don't have Octave available at the moment to try it out, but I believe that the following would do it:
B = A(A{:,1} == 1234,:);
When dealing with cells () returns the cell, {} returns the contents of the cell.

Related

Getting an empty result for newQuery

I've a problem in getting the value of the query $scholars for $lt = $scholars->lat.The result is empty array for dd($lt);
.Any help would be helpful to my school project.
database of Scholar
id lat lng scholar_birthday scholar_GPA
1 10.275667 123.8569163 1995-12-12 89
2 10.2572114 123.839243 2000-05-05 88
3 9.9545909 124.1368558 2002-05-05 89
4 10.1208564 124.8495005 2010-05-05 85
$scholars = (new Scholar)->newQuery()->select('*');
$scholars->whereBetween(DB::raw('TIMESTAMPDIFF(YEAR,scholars.scholar_birthday,CURDATE())'),array($ship_age_from,$ship_age_to));
$scholars->whereBetween(DB::raw('scholar_GPA'),array($ship_gpa_from,$ship_gpa_to));
$lt = $scholars->lat;
$lg = $scholars->lng;
$str = $lt.','.$lg;
$url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($lt).','.trim($lg).'&sensor=false';
$json = #file_get_contents($url);
$data=json_decode($json);
$status = $data->status;
$data->results[0]->formatted_address;
dd($lt);
$scholars = $scholars->get();
dd Result
Undefined property: Illuminate\Database\Eloquent\Builder::$lat
Two things,
when you use the newQuery() you will still need to get() the result like such
$scholars = (new Scholar)->newQuery()->select('*')->get();
This however will retrieve a collection and not a single result so you will need to loop over this.
foreach($scholars as $scholar){
$lt = $scholars->lat;
dd($lt);
}

Why isn't my return statement working?

I have a function that converts a decimal value to binary. I understand I have the logic correct as I can get it to work outside of a function.
def decimaltobinary(value):
invertedbinary = []
value = int(value)
while value >= 1:
value = (value / 2)
invertedbinary.append(value)
value = int(value)
for n, i in enumerate(invertedbinary):
if (round(i) == i):
invertedbinary[n] = 0
else:
invertedbinary[n] = 1
invertedbinary.reverse()
value = ''.join(str(e) for e in invertedbinary)
return value
decimaltobinary(firstvalue)
print (firstvalue)
decimaltobinary(secondvalue)
print (secondvalue)
Let's say firstvalue = 5 and secondvalue = 10. The values returned each time the function is executed should be 101 and 1010 respectively. However, the values I get printed are the starting values of five and ten. Why is this happening?
The code works as expected, but you didn't assign the returned value:
>>> firstvalue = decimaltobinary(5)
>>> firstvalue
'101'
Note that there are easier ways to accomplish your goal:
>>> str(bin(5))[2:]
'101'
>>> "{0:b}".format(10)
'1010'

How to get working variables out of a function in F#

I have a function in F# , like:
let MyFunction x =
let workingVariable1 = x + 1
let workingVariable2 = workingVariable1 + 1
let y = workingVariable2 + 1
y
Basically, MyFunction takes an input x and returns y. However, in the process of calculation, there are a few working variables (intermediate variables), and due to the nature of my work (civil engineering), I need to report all intermediate results. How should I store all working variables of the function ?
I'm not exactly sure what kind of "report" your are expecting. Is this a log of intermediate values ? How long time this log should be kept ? etc. etc This is my attempt from what I understand. It is not ideal solution because it allows to report values of intermediate steps but without knowing exactly which expression has generated the intermediate value (I think that you would like to know that a value n was an output of workingVariable1 = x + 1 expression).
So my solution is based on Computation Expressions. Computation expression are a kind of F# "monads".
First you need to define a computation expression :
type LoggingBuilder() =
let log p = printfn "intermediate result %A" p
member this.Bind(x, f) =
log x
f x
member this.Return(x) =
x
Next we create an instance of computation expression builder :
let logIntermediate = new LoggingBuilder()
Now you can rewrite your original function like this:
let loggedWorkflow x =
logIntermediate
{
let! workingVariable1 = x + 1
let! workingVariable2 = workingVariable1 + 1
let! y = workingVariable2 + 1
return y,workingVariable1,workingVariable2
}
If you run loggedWorkflow function passing in 10 you get this result :
> loggedWorkflow 10;;
intermediate result 11
intermediate result 12
intermediate result 13
val it : int * int * int = (13, 11, 12)
As I said your intermediate values are logged, however you're not sure which line of code is responsible for.
We could however enchance a little bit to get the FullName of the type with a corresponding line of code. We have to change a little our computation expression builder :
member this.Bind(x, f) =
log x (f.GetType().FullName)
f x
and a log function to :
let log p f = printfn "intermediate result %A %A" p f
If you run again loggedWorkflow function passing in 10 you get this result (this is from my script run in FSI) :
intermediate result 11 "FSI_0003+loggedWorkflow#34"
intermediate result 12 "FSI_0003+loggedWorkflow#35-1"
intermediate result 13 "FSI_0003+loggedWorkflow#36-2"
This is a hack but we get some extra information about where the expressions like workingVariable1 = x + 1 were definied (in my case it is "FSI_") and on which line of code (#34, #35-1). If your code changes and this is very likely to happen, your intermediate result if logged for a long time will be false. Note that I have not tested it outside of FSI and don't know if lines of code are included in every case.
I'm not sure if we can get an expression name (like workingVariable1 = x + 1) to log from computation expression. I think it's not possible.
Note: Instead of log function you coud define some other function that persist this intermediate steps in a durable storage or whatever.
UPDATE
I've tried to came up with a different solution and it is not very easy. However I might have hit a compromise. Let me explain. You can't get a name of value is bound to inside a computation expression. So we are not able to log for example for expression workingVariable1 = x + 1 that "'workingVariable1' result is 2". Let say we pass into our computation expression an extra name of intermediate result like that :
let loggedWorkflow x =
logIntermediate
{
let! workingVariable1 = "wk1" ## x + 1
let! workingVariable2 = "wk2" ## workingVariable1 + 1
let! y = "y" ## workingVariable2 + 1
return y,workingVariable1,workingVariable2
}
As you can see before ## sign we give the name of the intermediate result so let! workingVariable1 = "wk1" ## x + 1 line will be logged as "wk1".
We need then an extra type which would store a name and a value of the expression :
type NamedExpression<'T> = {Value:'T ; Name: string}
Then we have to redefine an infix operator ## we use une computation expression :
let (##) name v = {Value = v; Name = name}
This operator just takes left and right part of the expression and wraps it within NamedExpression<'T> type.
We're not done yet. We have to modify the Bind part of our computation expression builder :
member this.Bind(x, f) =
let {Name = n; Value = v} = x
log v n
f v
First we deconstruct the NamedExpression<'T> value into name and wraped value. We log it and apply the function f to the unwrapped value v. Log function looks like that :
let log p n = printfn "'%s' has intermediate result of : %A" n p
Now when you run the workflow loggedWorkflow 10;; you get the following result :
'wk1' has intermediate result of : 11
'wk2' has intermediate result of : 12
'y' has intermediate result of : 13
Maybe there are better way to do that, something with compiler services or so, but this is the best attempt I could do so far.
If I understand you correctly, then there are several options:
let MyFunction1 x =
let workingVariable1 = x + 1
let workingVariable2 = workingVariable1 + 1
let y = workingVariable2 + 1
y,workingVariable1,workingVariable2
MyFunction1 2 |> printfn "%A"
type OneType()=
member val Y = 0 with get,set
member val WV1 = 0 with get,set
member val WV2 = 0 with get,set
override this.ToString() =
sprintf "Y: %d; WV1: %d; WV2: %d\n" this.Y this.WV1 this.WV2
let MyFunction2 x =
let workingVariable1 = x + 1
let workingVariable2 = workingVariable1 + 1
let y = workingVariable2 + 1
new OneType(Y=y,WV1=workingVariable1,WV2=workingVariable2)
MyFunction2 2 |> printfn "%A"
Out:
(5, 3, 4)
Y: 5; WV1: 3; WV2: 4
http://ideone.com/eYNwYm
In the first function uses the tuple:
https://msdn.microsoft.com/en-us/library/dd233200.aspx
The second native data type.
https://msdn.microsoft.com/en-us/library/dd233205.aspx
It's not very "functional" way, but you can use mutable variable to store intermediate results:
let mutable workingVariable1 = 0
let mutable workingVariable2 = 0
let MyFunction x =
workingVariable1 <- x + 1
workingVariable2 <- workingVariable1 + 1
let y = workingVariable2 + 1
y

octave: using find() on cell array {} subscript and assigning it to another cell array

This is an example in Section 6.3.1 Comma Separated Lists Generated from Cell Arrays of the Octave documentation (I browsed it through the doc command on the Octave prompt) which I don't quite understand.
in{1} = [10, 20, 30, 40, 50, 60, 70, 80, 90];
in{2} = inf;
in{3} = "last";
in{4} = "first";
out = cell(4, 1);
[out{1:3}] = find(in{1 : 3}); % line which I do not understand
So at the end of this section, we have in looking like:
in =
{
[1,1] =
10 20 30 40 50 60 70 80 90
[1,2] = Inf
[1,3] = last
[1,4] = first
}
and out looking like:
out =
{
[1,1] =
1 1 1 1 1 1 1 1 1
[2,1] =
1 2 3 4 5 6 7 8 9
[3,1] =
10 20 30 40 50 60 70 80 90
[4,1] = [](0x0)
}
Here, find is called with 3 output parameters (forgive me if I'm wrong on calling them output parameters, I am pretty new to Octave) from [out{1:3}], which represents the first 3 empty cells of the cell array out.
When I run find(in{1 : 3}) with 3 output parameters, as in:
[i,j,k] = find(in{1 : 3})
I get:
i = 1 1 1 1 1 1 1 1 1
j = 1 2 3 4 5 6 7 8 9
k = 10 20 30 40 50 60 70 80 90
which kind of explains why out looks like it does, but when I execute in{1:3}, I get:
ans = 10 20 30 40 50 60 70 80 90
ans = Inf
ans = last
which are the 1st to 3rd elements of the in cell array.
My question is: Why does find(in{1 : 3}) drop off the 2nd and 3rd entries in the comma separated list for in{1 : 3}?
Thank you.
The documentation for find should help you answer your question:
When called with 3 output arguments, find returns the row and column indices of non-zero elements (that's your i and j) and a vector containing the non-zero values (that's your k). That explains the 3 output arguments, but not why it only considers in{1}. To answer that you need to look at what happens when you pass 3 input arguments to find as in find (x, n, direction):
If three inputs are given, direction should be one of "first" or
"last", requesting only the first or last n indices, respectively.
However, the indices are always returned in ascending order.
so in{1} is your x (your data if you want), in{2} is how many indices find should consider (all of them in your case since in{2} = Inf) and {in3}is whether find should find the first or last indices of the vector in{1} (last in your case).

Convert decimal number to excel-header-like number

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
0 = A
1 = B
...
25 = Z
26 = AA
27 = AB
...
701 = ZZ
702 = AAA
I cannot think of any solution that does not involve loop-bruteforce :-(
I expect a function/program, that accepts a decimal number and returns a string as a result.
Haskell, 78 57 50 43 chars
o=map(['A'..'Z']:)$[]:o
e=(!!)$o>>=sequence
Other entries aren't counting the driver, which adds another 40 chars:
main=interact$unlines.map(e.read).lines
A new approach, using a lazy, infinite list, and the power of Monads! And besides, using sequence makes me :), using infinite lists makes me :o
If you look carefully the excel representation is like base 26 number but not exactly same as base 26.
In Excel conversion Z + 1 = AA while in base-26 Z + 1 = BA
The algorithm is almost same as decimal to base-26 conversion with just once change.
In base-26, we do a recursive call by passing it the quotient, but here we pass it quotient-1:
function decimalToExcel(num)
// base condition of recursion.
if num < 26
print 'A' + num
else
quotient = num / 26;
reminder = num % 26;
// recursive calls.
decimalToExcel(quotient - 1);
decimalToExcel(reminder);
end-if
end-function
Java Implementation
Python, 44 chars
Oh c'mon, we can do better than lengths of 100+ :
X=lambda n:~n and X(n/26-1)+chr(65+n%26)or''
Testing:
>>> for i in 0, 1, 25, 26, 27, 700, 701, 702:
... print i,'=',X(i)
...
0 = A
1 = B
25 = Z
26 = AA
27 = AB
700 = ZY
701 = ZZ
702 = AAA
Since I am not sure what base you're converting from and what base you want (your title suggests one and your question the opposite), I'll cover both.
Algorithm for converting ZZ to 701
First recognize that we have a number encoded in base 26, where the "digits" are A..Z. Set a counter a to zero and start reading the number at the rightmost (least significant digit). Progressing from right to left, read each number and convert its "digit" to a decimal number. Multiply this by 26a and add this to the result. Increment a and process the next digit.
Algorithm for converting 701 to ZZ
We simply factor the number into powers of 26, much like we do when converting to binary. Simply take num%26, convert it to A..Z "digits" and append to the converted number (assuming it's a string), then integer-divide your number. Repeat until num is zero. After this, reverse the converted number string to have the most significant bit first.
Edit: As you point out, once two-digit numbers are reached we actually have base 27 for all non-least-significant bits. Simply apply the same algorithms here, incrementing any "constants" by one. Should work, but I haven't tried it myself.
Re-edit: For the ZZ->701 case, don't increment the base exponent. Do however keep in mind that A no longer is 0 (but 1) and so forth.
Explanation of why this is not a base 26 conversion
Let's start by looking at the real base 26 positional system. (Rather, look as base 4 since it's less numbers). The following is true (assuming A = 0):
A = AA = A * 4^1 + A * 4^0 = 0 * 4^1 + 0 * 4^0 = 0
B = AB = A * 4^1 + B * 4^0 = 0 * 4^1 + 1 * 4^0 = 1
C = AC = A * 4^1 + C * 4^0 = 0 * 4^1 + 2 * 4^0 = 2
D = AD = A * 4^1 + D * 4^0 = 0 * 4^1 + 3 * 4^0 = 3
BA = B * 4^0 + A * 4^0 = 1 * 4^1 + 0 * 4^0 = 4
And so forth... notice that AA is 0 rather than 4 as it would be in Excel notation. Hence, Excel notation is not base 26.
In Excel VBA ... the obvious choice :)
Sub a()
For Each O In Range("A1:AA1")
k = O.Address()
Debug.Print Mid(k, 2, Len(k) - 3); "="; O.Column - 1
Next
End Sub
Or for getting the column number in the first row of the WorkSheet (which make more sense, since we are in Excel ...)
Sub a()
For Each O In Range("A1:AA1")
O.Value = O.Column - 1
Next
End Sub
Or better yet: 56 chars
Sub a()
Set O = Range("A1:AA1")
O.Formula = "=Column()"
End Sub
Scala: 63 chars
def c(n:Int):String=(if(n<26)""else c(n/26-1))+(65+n%26).toChar
Prolog, 109 123 bytes
Convert from decimal number to Excel string:
c(D,E):- d(D,X),atom_codes(E,X).
d(D,[E]):-D<26,E is D+65,!.
d(D,[O|M]):-N is D//27,d(N,M),O is 65+D rem 26.
That code does not work for c(27, N), which yields N='BB'
This one works fine:
c(D,E):-c(D,26,[],X),atom_codes(E,X).
c(D,B,T,M):-(D<B->M-S=[O|T]-B;(S=26,N is D//S,c(N,27,[O|T],M))),O is 91-S+D rem B,!.
Tests:
?- c(0, N).
N = 'A'.
?- c(27, N).
N = 'AB'.
?- c(701, N).
N = 'ZZ'.
?- c(702, N).
N = 'AAA'
Converts from Excel string to decimal number (87 bytes):
x(E,D):-x(E,0,D).
x([C],X,N):-N is X+C-65,!.
x([C|T],X,N):-Y is (X+C-64)*26,x(T,Y,N).
F# : 166 137
let rec c x = if x < 26 then [(char) ((int 'A') + x)] else List.append (c (x/26-1)) (c (x%26))
let s x = new string (c x |> List.toArray)
PHP: At least 59 and 33 characters.
<?for($a=NUM+1;$a>=1;$a=$a/26)$c=chr(--$a%26+65).$c;echo$c;
Or the shortest version:
<?for($a=A;$i++<NUM;++$a);echo$a;
Using the following formula, you can figure out the last character in the string:
transform(int num)
return (char)num + 47; // Transform int to ascii alphabetic char. 47 might not be right.
char lastChar(int num)
{
return transform(num % 26);
}
Using this, we can make a recursive function (I don't think its brute force).
string getExcelHeader(int decimal)
{
if (decimal > 26)
return getExcelHeader(decimal / 26) + transform(decimal % 26);
else
return transform(decimal);
}
Or.. something like that. I'm really tired, maybe I should stop answering questions and go to bed :P