Convert cell arrays into single array - mysql

Getting started with Matlab and mySQL, as a result for my query I get this type of array:
my_result =
5×1 cell array
{'a'}
{'b'}
{'c'}
{'d'}
{'e'}
I'd like to get a simple array like this:
[a, b, c, d, e]
Here's my code:
mysql( 'open', 'my_database', 'usr','passw' )
query = fileread('query1.sql');
query = sprintf(query)
my_result = mysql(query);
And my attempts at getting a simple array:
my_array = []
for i=1:length(my_result)
my_array = [my_array, my_result{i}];
end
>> my_array
my_array =
'abcde'
>> cell2mat(my_result)
Error using cat
Dimensions of arrays being concatenated are not consistent.
Error in cell2mat (line 83)
m{n} = cat(1,c{:,n});
Is there a way to either get the correct format in the first place, or easily convert it properly? Thank you

just use the cell2mat built-in function
a{1} = 'a'
a{2} = 'b'
a{3} = 'c'
a{4} = 'd'
a{5} = 'e'
a =
5×1 cell array
{'a'}
{'b'}
{'c'}
{'d'}
{'e'}
cell2mat(a)
ans =
5×1 char array
'a'
'b'
'c'
'd'
'e'

Related

COUNTIFS: Excel to pandas and remove counted elements

I have a COUNTIFS equation in excel (COUNTIFS($A$2:$A$6, "<=" & $C4))-SUM(D$2:D3) where A2toA6 is my_list. C4 is current 'bin' with the condition and D* are previous summed results from my_list that meet the condition. I am attempting to implement this in Python
I have looked at previous COUNTIF questions but I am struggling to complete the final '-SUM(D$2:D3)' part of the code.
See the COUNTIFS($A$2:$A$6, "<=" & $C4) section below.
'''
my_list=(-1,-0.5, 0, 1, 2)
bins = (-1, 0, 1)
out = []
for iteration, num in enumerate(bins):
n = []
out.append(n)
count = sum(1 for elem in my_list if elem<=(num))
n.append(count)
print(out)
'''
out = [1, [3], [4]]
I need to sum previous elements, that have already been counted, and remove these elements from the next count so that they are not counted twice ( Excel representation -SUM(D$2:D3) ). This is where I need some help! I used enumerate to track iterations. I have tried the code below in the same loop but I can't resolve this and I get errors:
'''
count1 = sum(out[0:i[0]]) for i in (out)
and
count1 = out(n) - out(n-1)
''''
See expected output values in 'out' array for bin conditions below:
I was able to achieve the required output array values by creating an additional if/elif statement to factor out previous array elements and generate a new output array 'out1'. This works but may not be the most efficient way to achieve the end goal:
'''
import numpy as np
my_list=(-1,-0.5, 0, 1, 2)
#bins = np.arange(-1.0, 1.05, 0.05)
bins = (-1, 0, 1)
out = []
out1 = []
for iteration, num in enumerate(bins):
count = sum(1 for elem in my_list if elem<=(num))
out.append(count)
if iteration == 0:
count1 = out[iteration]
out1.append(count1)
elif iteration > 0:
count1 = out[iteration] - out[iteration - 1]
out1.append(count1)
print(out1)
'''
I also tried using the below code as suggested in other answers but this didn't work for me:
'''
-np.diff([out])
print(out)
'''

Use varargin for multiple arguments with default values in MATLAB

Is there a way to supply arguments using varargin in MATLAB in the following manner?
Function
func myFunc(varargin)
if a not given as argument
a = 2;
if b not given as argument
b = 2;
if c not given as argument
c = a+b;
d = 2*c;
end
I want to call the above function once with b = 3 and another time while the previous one is running in the same command window with a = 3 and c = 3 and letting b take the default value in the function this time. How can it be done using varargin?
Here's the latest and greatest way to write the function (using arguments blocks from R2019b)
function out = someFcn(options)
arguments
options.A = 3;
options.B = 7;
options.C = [];
end
if isempty(options.C)
options.C = options.A + options.B;
end
out = options.A + options.B + options.C;
end
Note that this syntax does not allow you to say options.C = options.A + options.B directly in the arguments block.
In MATLAB < R2021a, you call this like so
someFcn('A', 3)
In MATLAB >= R2021a, you can use the new name=value syntax
someFcn(B = 7)
Here are two ways to do this which have been available since 2007a (i.e. a long time!). For a much newer approach, see Edric's answer.
Use nargin and ensure your inputs are always in order
Use name-value pairs and an input parser
nargin: slightly simpler but relies on consistent input order
function myFunc( a, b, c )
if nargin < 1 || isempty(a)
a = 2;
end
if nargin < 2 || isempty(b)
b = 2;
end
if nargin < 3 || isempty(c)
c = a + b;
end
end
Using the isempty check you can optionally provide just later arguments, for example myFunc( [], 4 ) would just set b=4 and use the defaults otherwise.
inputParser: more flexible but can't directly handle the c=a+b default
function myFunc( varargin )
p = inputParser;
p.addOptional( 'a', 2 );
p.addOptional( 'b', 2 );
p.addOptional( 'c', NaN ); % Can't default to a+b, default to NaN
p.parse( varargin{:} );
a = p.Results.a;
b = p.Results.b;
c = p.Results.c;
if isnan(c) % Handle the defaulted case
c = a + b;
end
end
This would get used like myFunc( 'b', 4 );. This approach is also agnostic to the input order because of the name-value pairs, so you can also do something like myFunc( 'c', 3, 'a', 1 );

Function with vector as argument in Octave

How can I make a function with a vector as input and a matrix as an output?
I have to write a function that will convert cubic meters to liters and English gallons. The input should be a vector containing volume values ​​in m ^ 3 to be converted. The result should be a matrix in which the first column contains the result in m ^ 3, the second liter, the third English gallon.
I tried this:
function [liter, gallon] = function1 (x=[a, b, c, d]);
liter= a-10+d-c;
gallon= b+15+c;
endfunction
You're almost there.
The x=[a,b,c,d] part is superfluous, your argument should be just x.
function [liter, gallon] = function1 (x);
a = x(1); b = x(2); c = x(3); d = x(4);
liter = a - 10 + d - c;
gallon = b + 15 + c;
endfunction
If you want your code to be safe and guard against improper inputs, you can perform such checks manually inside the function, e.g.
assert( nargin < 1 || nargin > 4, "Wrong number of inputs supplied");
The syntax x=[a,b,c,d] does not apply to octave; this is reserved for setting up default arguments, in which case a, b, c, and d should be given specific values that you'd want as the defaults. if you had said something like x = [1,2,3,4], then this would be fine, and it would mean that if you called the function without an argument, it would set x up to this default value.

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'

Lua: Functions with Tables for Beginners - Proper Naming/Retrieving of Tables within Tables

I am having a horrible time at grasping functions and tables. I've asked a question before that is similar to this but still am having problems getting this to work properly. So I will be more descriptive. But just when I think I understand it I completely confuse myself again. Here is what I am trying to accomplish:
I have a program that is receiving its input from an outside source. It needs to take that input, and basically "dissect" the strings to get the required information. Based on the information it receives, it moves onto the next phase or functions to do the appropriate actions. For example:
input is received as NY345,de,M,9900
I created a table that has all of the different ways the specific input can begin, such as:
local t = {["NY"] = 5, ["MS"] = 7, ["HG"] = 10, ["JX"] = 14, ["UY"] = 20}
Now I want to use a function to receive the input and look for k in t{} and use that to gather other variables...
function seek(input)
for k, v in pairs (seek) do
local info = string.match(input,k)
if info then
return {seekData = string.match(input,k..",(%d*),.*"), seekMult = seekData*v}
end
end
end
How far off am I?
If I had the table "t = {...}" above, and that contained other tables; how can I name each table inside of "t = {...}" and retrieve it for other equations? Such as if ["a"] = 8, the rest of that table was to be utilized? For example:
t={["a"] = 2, ["b"] = 3, ["c"] = "IOS"},{["a"] = 8, ["b"] = 9, ["c"] = "NVY"},{["a"] = 1, ["b"] = 5, ["c"] = "CWQ"}}
if a = 8, then b = 9 and c = "NVY"
I would like my function to search k (of each table) and compare it with the input. If that was found, then it would set the other two local variables to b and c?
Thanks for your help!
I will only answer question 1, as 2 and 3 should be separate questions. There are many ways to do this based on specifics you don't mention but assuming you have a table t like this:
t={
{["a"] = 2, ["b"] = 3, ["c"] = "IOS"},
{["a"] = 8, ["b"] = 9, ["c"] = "NVY"},
{["a"] = 1, ["b"] = 5, ["c"] = "CWQ"}
}
then a function that takes an a key value to look for and returns b and c:
function findItem(a, yourTable)
for i,tt in ipairs(yourTable) do
if tt.a == a then
return i, tt.b, tt.c
end
end
end
With this, if the input is k, then
i, b, c = findItem(k, t)
if i == nil then
print('could not find k')
else
print('found k at index ' .. i)
end
The findItem could of course just return the subtable found, and maybe you don't need index:
function findItem(a, yourTable)
for i,tt in ipairs(yourTable) do
if tt.a == a then
return tt
end
end
end