Matlab structure arrays treated as vectors - arrays

I'd like my program to not treat this:
{0:1000}
{ones(1,1000)}
not as vectors when I input them for my structure array. Any idea on how to do this? Thanks in advance.

if you want a complete other action of the function depending on the input type, you'll have to write a wrapper, catching off this input type. This is possible with the isa function. It works as follows
if isa(var,'double')
% do something with the double
elseif isa(var,'struct')
% do something with the structure
else
% ...
end
OR
maybe it's possible to avoid this wrapping and treat all variables alike, but then you'll have to provide a bit more information about this function and what you want it to do...

Related

Julia, use of map to run a function multiple times,

I have some code that runs fine and does what I want, although there may be a simpler more elegant solution, this works :
round(Int16, floor(rand(TruncatedNormal(150,20,50,250))))
However when I try to execute it multiple times, using map, it throws an error saying it doesn't like the Int16 specification, so this:
map(round(Int16, floor(rand(TruncatedNormal(150,20,50,250)))), 1:2)
throws this error
ERROR: MethodError: objects of type Int16 are not callable
I just want to run it twice (in this case) and sum the results. Why is it unhappy? Thx. J
The first argument to map is a function. So, with your code, Julia is trying to make a function call:
round(Int16, floor(rand(TruncatedNormal(150,20,50,250))))()
But the output of round(Int16, ...) isn't a function, it's a number, so you cannot call it. That's why the error says "objects of type Int16 are not callable." You could fix this by using an anonymous function:
map(() -> round(Int16, floor(rand(TruncatedNormal(150,20,50,250)))), 1:2)
But the "Julian" way to do this is to use a comprehension:
[round(Int16, floor(rand(TruncatedNormal(150,20,50,250)))) for _ in 1:2]
EDIT:
If you are going to sum the results, then you can use something that looks like a comprehension but is called a generator expression. This is basically everything above with the [ ] around the expression. A generator expression can be used directly in functions like sum or mean, etc.
sum(round(Int16, floor(rand(TruncatedNormal(150,20,50,250)))) for _ in 1:2)
The advantage to generator expressions is that they don't allocate the memory for the full array. So, if you did this 100 times and used the sum approach above, you wouldn't need to allocate space for 100 numbers.
This goes beyond the original question, but OP wanted to use the sum expression where the 2 in 1:2 is a 1-element vector. Of course, if the input is always a 1-element vector, then I recommend first(x) like the comments. But this is a nice opportunity to show the importance of breaking things down into functions frequently in Julia. For example, you could take the entire sum expression and define a function
generatenumbers(n::Integer) = sum(... for _ in 1:n)
where n is a scalar. Then if you have some odd array expression for n (1-element vector, many such ns in a multi-dim array, etc.), you can just do:
generatenumbers.(ns)
# will apply to each element and return same shape as ns
If the de-sugaring logic is more complex than applying element-wise, you can even define:
generatenumbers(ns::AbstractArray) = # ... something more complex
The point is to define an "atomic" function that expresses the statement or task you want clearly, then use dispatch to apply it to more complicated data-structures that appear in practical code. This is a common design pattern in Julia (not the only option, but an effective one).
Adding on the answer from #darsnack.
If you want to run it multiple times in order to keep the results (it wasn't clear from the question). Then you could also ask rand to produce a vector by doing the following (and also making the type conversion through the floor call).
Moving from:
map(round(Int16, floor(rand(TruncatedNormal(150,20,50,250)))), 1:2)
to:
floor.(Int16, rand(TruncatedNormal(150,20,50,250), 2))
The documentation is here.

Easier way to call an absurd number of functions

So I'm calling a whole lot of functions what kind of have a similar pattern
(disclaimer:I did not write these)
They go like so:
Write_thing0<x>_object00<y>(somedata);
where <x> takes values from 0 to 6 and <y> takes values from 1 to 20.
Is there a sane way to do this, perhaps in a loop? The token-pasting operator was suggested but that doesn't work or I can't find a way to use it.
Edit:
Okay so I'll go into more depth:
Write_thing000_object001_A(uint8);
Write_thing000_object001_B(uint8);
Write_thing000_object001_C(uint16);
.................................
Write_thing000_object001_Z(uint8);
Write_thing000_object002_A(uint8);
.................................
Write_thing000_object002_Z(uint8);
/* all the way up to object 20, then thing changes to 001 and object count resets */
the pattern of parameters stays the same in each A-Z block.
I hope that makes more sense.
It can be done with x-macros:
#define CALL_ONE(i,j) call_func_##i##_##j(); // Put your function name here.
#define LIST_A(m,d) m(0,d) m(1,d) m(2,d) // Replace 0,1,2 with actual values.
#define LIST_B(m,d) m(X,d) m(Y,d) m(Z,d) // Replace X,Y,Z with actual values.
#define CALL_A(x,unused) LIST_A(CALL_ONE,x)
#define CALL_B() LIST_B(CALL_A,)
Now, CALL_B() expands to:
call_func_0_X(); call_func_1_X(); call_func_2_X();
call_func_0_Y(); call_func_1_Y(); call_func_2_Y();
call_func_0_Z(); call_func_1_Z(); call_func_2_Z();
It should be easy to adapt this for your purposes.
From your example you seem to suggest that the code looks like this:
Write_thing000_object001(somedata);
Write_thing000_object002(somedata);
Write_thing000_object003(somedata);
Write_thing000_object004(somedata);
Write_thing000_object005(somedata);
/// lots of lines
Write_thing006_object0020(somedata);
If this is exactly what your code looks like fine. But it raises a lot of questions to me
1) Does some data stay the same for each function call (or set of calls)
2) Is every function name used or is a subset of names
3) What do all these functions do? It seems likely give the name that they could be all be rewritten like this:
Write_thing_object(somedata,x,y);
then you just have one function and you can put the whole thing in a loop -- why can't you do that?
Also as a side note, this is often called a 'dispatch pattern', if you simple make this function and have it call the correct other function. You could do this efficiently by creating a 2 dimension array of function pointers. If this is what you need to do I could show you how to do that.

Dynamic vector creation

I am trying to create a vector dynamically in dependence of n (for example 1 or 4). If my n is bigger I need to have more values in my vector.
for i=1:(N-n)
yvecT(i)=y(n+i); % Achtung, Zeilenvektor
for k=n:-1:1
F(i-1+n,:)=[-y(i) -y(i-k) u(i) u(i-k)];
end
end
%n=1 F(i,:)=[-y(i) u(i)];
%n=2 F(i,:)=[-y(i) -y(i-1) u(i) u(i-1)];
%n=4 F(i,:)=[-y(i) -y(i-1) -y(i-2) -y(i-3) u(i) u(i-1) u(i-2) u(i-3)];
it is a function used to identify a System....
You should have posted the for-loop (with the if-statements) from the link in the question and stated that you wanted it to work for an arbitary n. That would have made everyone understand your problem. I think the easiest way to do what you do is to use subreferencing. So in case n==2 we do not have
F(i-1,:)=[-y(i) -y(i-1) u(i) u(i-1)];
but rather,
F(i-(n-1),:)=[-y(i:-1:(n-1)) u(i:-1:(n-1))];
This looks messier, but it works for any arbitary n. Some other comments about the code. The variable i is also a function returning the imaginary unit. By naming a variable i you overload this function. The recommended way is to use 1i as an imaginary unit, so it is not critical, but in case you do not necessarily need i as a variable you should consider another name. Also it is easier for us to understand in case you write in english. So in general, prefer comments in english when posting here.

get fieldname of a data struct matlab

I have the following nested struct:
hole 1x200 struct, diam 1x12 struct, which has the following fields: pos, freq1, fre12
That is:
hole(1 to 200).diam(1 to 12).pos
.freq1
.freq2
From a value (freq1 and freq2), I would like to obtain the field name of the struct. So I will need to find the value that matches with freq1 and freq2 and show the fieldname.
I tried to use structfun in order to apply a function to each field.
[struct.field]=structfun(#(x) find(x.freq1==27.059783995484867 & freq2==76.468355874897000))
But I guess I am writing something wrong on the code.
Also I create an anonymous fuction but I have the following error:
'Error using structfun / Inputs to STRUCTFUN must be scalar
structures'
. How ever when I verified if an specific value of the struct is scalar, I have a positive answerd: isscalar(hole(130).diam(10))
I belive I more near the solution using this script:
myfun=#(yourarray,desiredvalue) yourarray==desiredvalue;
%//Apply function to each field of scalar structure, it SCALAR??
desiredfieldindex=myfun(structfun(#(x) x,hole),26.697046257785030)
desiredFieldName=fNames(desiredFieldIndex)
I don´t know if I am in the rigth path, or I should utilize the function find. ALso I that case I don´t know how to implement it.
Couple of things.
FLOATING POINT VALUES! Careful!! Never compare a floating point value as val==0.3! do abs(val-0.3)<10^-8 or something similar. Read more here.
You are using structfun wrong. The function needs 2 arguments, and you are just passing 1! However, structfun will apply a function to each field so you are not using it rigth either in that sense. Lets see an example
example:
a.hithere=5;
a.notthis=3;
fun=#(x)x==5;
[isfive]=structfun(fun,a)
isfive =
1
0
As you can see, it applies the function to each of them. If you try to change the function to fun=#(x)x.hithere==5 you will get an error! As the function is applied to each field, and x.hithere.hithere or x.notthis.hithere do not exist.
If you want to check both values, you will need to check them independently making two separated calls to structfun or avoiding structfun and just making a for loop.

Regex for refactoring to arrays

I have a very big C programming project that uses thousands of struct variables with this naming convention:
specificstruct->x = specificstruct->y + specificstruct->z
I want to do some heavy refactoring, namely converting most of these struct members to arrays. The code above would look like this:
specificstruct->x[i] = specificstruct->y[i] + specificstruct->z[i]
... and I don't feel like wasting an entire day on doing all this manually. Does anyone have a suitable regex in store?
EDIT: It is always the same struct, but the equations vary.
Thanks in advance!
Best regards,
P. Nilsson
I'm not sure about your particular case, but maybe Coccinelle can help you. It is a system for patching source code, based on some rules like "if x is an expression without function invocations, change x+x to 2*x" etc.
For a generalized approach something like this ought to do - the assumption is that you've got consistent spacing between your expressions
(.*?->.) = (.*?->.) \+ (.*?->.)
You can then write your new array structure as:
\1[i] = \2[i] + \3[i]
s/\(specificstruct->x\) = \(specificstruct->y\ )\+ \(specificstruct->z\)/\1[i] = \2[i] + \3[i]/g
If you're just looking for the name followed by -> then a single character, you could try
(?<struct>\w+)\s?->\s?(?<var>\w{1}) //single char after ->
(?<struct>\w+)\s?->\s?(?<var>\w+) //multiple char after ->
That way you have groups so you can compare the names before you do any replacements. The \s? helps to match even if you added spacing between some but not others.

Resources