Octave - accessing aray elements from within a function - octave
I want to populate an empty array, and then access individual elements from within a function.
a = [];
for i=1:10
a(i)=i;
end
function display_a(k)
a = a(k);
disp(a);
end
display_a(5)
Here I receive an error:
'a' undefined near line 8, column 7
Which means that a=a(k) within the function is not recognized as my array a. Any idea on how to pull this off?
I tried declaring a as a global variable. Apart from my understanding that declaring global variables is not a good practice, my function returns the whole array instead of just one, specified element.
Thank you in advance.
Related
Filling eltType with nil values
So I have a chapel issue i can't seem to figure out. I have a queue that one can set size. The only thing is is that it's setting size and filling the queue with a bunch of 0s (which make's sense). I'm trying to fill the queue with null rather than numerical values so later on when I work on the add method I can check if queue is null. I have attached an image of how everything is set up. Let me know if you guys have any guidance or ideas. The error that i'm getting is: error: type mismatch in assignment from string to int(64) I must be doing it the wrong way here.
The error you are seeing is about the line: elements[i] = 'nil'; 'nil' is a string, not the nil value, which is written as just nil without any quotes. Assigning a string to a slot in an array of int(64) doesn't work, so the compiler issues an error. In Chapel only classes can have a nil value though, so you'll need to use a different way to keep track of which positions in the elements array are filled. One way to do that would be to add two new integers to your class that keep track of the first and last positions containing valid values. As you add values to the queue the last position increases, and as you remove values the first position increases. When either of those values passes the end of the array, it wraps around back to the front. If last ever catches first, then the array is full. If first ever catches last then the array is empty. A few other things I think should be corrected in your code are: use semaphore.chpl; Use statements work with module names, not filenames, so this should probably be use semaphore;. If I'm understanding your intent here, this code is trying to set the size of the elements array to 5. var elementsDomain: domain(1); var elements: [elementsDomain] eltType = 5; The array's domain controls the size of the array, so the way to set the array size is through the domain: var elementsDomain: domain(1) = {0..#5}; var elements: [elementsDomain] eltType; elementsDomain = (0..capacity - 1); is setting elementsDomain to a range literal value. This works since the domain is 1-dimensional, but to make it more clear, you can set it to a domain literal value instead: {0..capacity - 1}.
Getting all functions in a Lua script
I'm trying to figure out a way to get all functions in a Lua script. This script has been compiled into a function through loadfile. For example, I'd want to get every function defined in the script below. function example1() end local function example2() end local library = {} function library:example3() end (function() -- Functions like this too. end) The names aren't important, I'm just looking for a way to get the actual functions so I can use them in debug.getinfo and get information like the lines they were defined in. I have LuaJIT, if that makes this any easier. Is something like this even possible? Thanks in advance.
I guess the file declares its functions as global, or it would be really easy to track what is returned. If that's the case, you can cycle through all the global items with a generic for loop, and only take the functions from them: allFuncs = {} for key, item in pairs(_G) do if type(item) == "function" then allFuncs[#allFuncs + 1] = item end end (_G is the table holding all the global variables) Then you will have a list (allFuncs) holding all the functions declared, but be aware that it will also contain default functions like setmetatable or xpcall. It's easy to modify the code to not make this happen, but only use this for testing / learning: function allFuncs() local funcsTab = {} for key, item in pairs(_G) do if type(item) == "function" then funcsTab[#funcsTab + 1] = item end end return funcsTab end defaultFuncs = allFuncs() --then you load your file: other functions get declared --we create another table containg the default + the new functions myFuncs = allFuncs() --then you subtract the first table from the second for i = 1, #myFuncs do for o = 1, #defaultFuncs do if myFuncs[i] == defaultFuncs[o] then table.remove(myFuncs, i) end end end This is if your file doesn't return anything and declares its functions as globals. If the file declares them as local and then returns a table containing them, just use the first piece of code replacing _G with that returned table.
This is not likely to be possible without syntax or bytecode analysis as each function definition is an assignment (just has different forms in your examples). See the bytecode inspector and a related discussion here. For the syntax analysis you can use metalua or something like lua-loose-parser. Keep in mind that even those tools won't give you the entire list of functions as some functions may be defined dynamically using loadstring (or similar methods). If you only have access to the result of loadfile, then you best bet is to use the bytecode analyzer.
This is possible using jit.attach in LuaJIT. You can attach callbacks to a number of compiler events with jit.attach. The callback can be called: when a function has been compiled to bytecode ("bc"); when trace recording starts or stops ("trace"); as a trace is being recorded ("record"); or when a trace exits through a side exit ("texit"). http://wiki.luajit.org/JIT-Compiler-API#jit-attach jit.attach(function(f) local funcInfo = jit.util.funcinfo(f) end, "bc")
In Ethereum Solidity, when changing an array length, I get "Value must be an lvalue". Why?
In Solidity, you can increase the size of an array to make room for a new member by using array.length++. But I'm getting an error: Value must be an lvalue
You can resize a dynamic array in storage (i.e. an array declared at the contract level) with “arrayname.length = ;” But if you get the “lvalue” error, you are probably doing one of two things wrong. You might be trying to resize an array in memory, or You might be trying to resize a non-dynamic array. int8[] memory somearray; // CASE 1 somearray.length++; // illegal int8[5] somearray; // CASE 2 somearray.length++; // illegal IMPORTANT NOTE: In Solidity, arrays are declared backwards from the way you’re probably used to declaring them. And if you have a >=2D array with some dynamic and some non-dynamic components, you may violate #2 and not understand why. Note also that arrays are accessed the “normal” way. Here's are some examples of this "backward" declaration paradigm in action: int8[][5] somearray; // This is 5 dyn arrays, NOT a dyn array-of-arrays w/len=5 // so... somearray[4]; // the last dynamic array somearray[1][12]; // the 13th element of the second dynamic array // thus... somearray.length++; // illegal. This array has length 5. Always. somearray[0].length++;// legal
Encountered same issue and what I had to was use the storage keyword since I was trying to modify a global storage array. bytes32[] storage someArray = someGlobalStorageArray;
'Invalid Handle object' when using a timer inside a function in MatLab
I am using a script in MatLab that works perfectly fine by itself, but I need to make a function out of it. The script read a .csv file, extract all values, start a timer, and at each tick displays the corresponding coordinates extracted from the .csv, resulting in a 3D animation of my graph. What I would like is to give it the location of the .csv, so that it starts displaying the graphs for this csv. Here is what I have come up with: function handFig(fileLoc) csv=csvread(fileLoc,1,0); both = csv(:,2:19); ax=axes; set(ax,'NextPlot','replacechildren'); Dt=0.1; %sampling period in secs k=1; hp1=text(both(k,1),both(k,2),both(k,3),'thumb'); %get handle to dot object hold on; hp2=text(both(k,4),both(k,5),both(k,6),'index'); hp3=text(both(k,7),both(k,8),both(k,9),'middle'); hp4=text(both(k,10),both(k,11),both(k,12),'ring'); hp5=text(both(k,13),both(k,14),both(k,15),'pinky'); hp6=text(both(k,16),both(k,17),both(k,18),'HAND'); L1=plot3([both(k,1),both(k,16)],[both(k,2),both(k,17)],[both(k,3),both(k,18)]); L2=plot3([both(k,4),both(k,16)],[both(k,5),both(k,17)],[both(k,6),both(k,18)]); L3=plot3([both(k,7),both(k,16)],[both(k,8),both(k,17)],[both(k,9),both(k,18)]); L4=plot3([both(k,10),both(k,16)],[both(k,11),both(k,17)],[both(k,12),both(k,18)]); L5=plot3([both(k,13),both(k,16)],[both(k,14),both(k,17)],[both(k,15),both(k,18)]); hold off; t1=timer('TimerFcn','k=doPlot(hp1,hp2,hp3,hp4,hp5,hp6,L1,L2,L3,L4,L5,both,t1,k)','Period', Dt,'ExecutionMode','fixedRate'); start(t1); end And the doplot function used: function k=doPlot(hp1,hp2,hp3,hp4,hp5,hp6,L1,L2,L3,L4,L5,pos,t1,k) k=k+1; if k<5000%length(pos) set(hp1,'pos',[pos(k,1),pos(k,2),pos(k,3)]); axis([0 255 0 255 0 255]); set(hp2,'pos',[pos(k,4),pos(k,5),pos(k,6)]); set(hp3,'pos',[pos(k,7),pos(k,8),pos(k,9)]); set(hp4,'pos',[pos(k,10),pos(k,11),pos(k,12)]); set(hp5,'pos',[pos(k,13),pos(k,14),pos(k,15)]); set(hp6,'pos',[pos(k,16),pos(k,17),pos(k,18)]); set(L1,'XData',[pos(k,1),pos(k,16)],'YData',[pos(k,2),pos(k,17)],'ZData',[pos(k,3),pos(k,18)]); set(L2,'XData',[pos(k,4),pos(k,16)],'YData',[pos(k,5),pos(k,17)],'ZData',[pos(k,6),pos(k,18)]); set(L3,'XData',[pos(k,7),pos(k,16)],'YData',[pos(k,8),pos(k,17)],'ZData',[pos(k,9),pos(k,18)]); set(L4,'XData',[pos(k,10),pos(k,16)],'YData',[pos(k,11),pos(k,17)],'ZData',[pos(k,12),pos(k,18)]); set(L5,'XData',[pos(k,13),pos(k,16)],'YData',[pos(k,14),pos(k,17)],'ZData',[pos(k,15),pos(k,18)]); else k=1; set(hp1,'pos',[pos(k,1),pos(k,2),pos(k,3)]); axis([0 255 0 255 0 255]); set(hp2,'pos',[pos(k,4),pos(k,5),pos(k,6)]); set(hp3,'pos',[pos(k,7),pos(k,8),pos(k,9)]); set(hp4,'pos',[pos(k,10),pos(k,11),pos(k,12)]); set(hp5,'pos',[pos(k,13),pos(k,14),pos(k,15)]); set(hp6,'pos',[pos(k,16),pos(k,17),pos(k,18)]); end However, when I run handFig('fileName.csv'), I obtain the same error everytime: ??? Error while evaluating TimerFcn for timer 'timer-7' Invalid handle object. I figured that it might come from the function trying to create a new 'csv' and 'both' everytime, so I tried removing them, and feeding the function the data directly, without results. What is exactly the problem? Is there a solution? Thanks a lot!
I think it's because when you call doPlot in the timer for the first time, you pass in t1 as an argument, and it might not exist the first time. Does doPlot need t1 at all? I'd suggest modifying it so it's not used, and then your call to: t1=timer('TimerFcn','k=doPlot(hp1,hp2,hp3,hp4,hp5,hp6,L1,L2,L3,L4,L5,both,k)','Period', Dt,'ExecutionMode','fixedRate'); Note the missing t1 in the doPlot call. Either that, or initialise your t1 before you create the timer so it has some value to pass in. Update (as an aside, can you use pause(Dct) in a loop instead? seems easier) Actually, now I think it's a problem of scope. It took a bit of digging to get to this, but looking at the Matlab documentation for function callbacks, it says: When MATLAB evaluates function handles, the same variables are in scope as when the function handle was created. (In contrast, callbacks specified as strings are evaluated in the base workspace.) You currently give your TimerFcn argument as a string, so k=doPlot(...) is evaluated in the base workspace. If you were to go to the matlab prompt, run handFig, and then type h1, you'd get an error because h1 is not available in the global workspace -- it's hidden inside handFig. That's the problem you're running into. However, the workaround is to specify your function as a function handle rather than a string (it says function handles are evaluated in the scope in which they are created, ie within handFig). Function handles to TimerFcn have to have two arguments obj and event (see Creating Callback Functions). Also, that help file says you have to put doPlot in its own m-file to have it not evaluate in the base Matlab workspace. In addition to these two required input arguments, your callback function can accept application-specific arguments. To receive these input arguments, you must use a cell array when specifying the name of the function as the value of a callback property. For more information, see Specifying the Value of Callback Function Properties. It goes through an example of what you have to do to get this working. Something like: % create timer t = timer('Period', Dt,'ExecutionMode','fixedRate'); % attach `k` to t so it can be accessed within doPlot set(t,'UserData',k); % specify TimerFcn and its extra arguments: t.TimerFcn = { #doPlot, hp1, hp2, hp3, ...., both }; start(t) Note -- the reason k is set in UserData is because it needs to be somehow saved and modified between calls to doPlot. Then modify your doPlot to have two arguments at the beginning (which aren't used), and not accept the k argument. To extract k you do get(timer_obj,'UserData') from within doPlot: function k=doPlot(timer_obj, event, hp1,hp2,hp3,.....) k = get(timer_obj,'UserData'); .... % rest of code here. % save back k so it's changed for next time! set(timer_obj,'UserData',k); I think that's on the right track - play around with it. I'd highly recommend the mathworks forums for this sort of thing too, those people are whizzes. This thread from the mathworks forum was what got me started and might prove helpful to you. Good luck!
Function definitions are not permitted in this context
Ok, I am new in Matlab and I am currently working on some econometric script. Before I move to real econometrics I have to create a function that selects the data that I'm interested in. Although I managed to get that script to work by writing at a very structural level, I would like this script to be as universal as possible and therefore would like to divide it into specific functions. However, when I converted all this to one function, I keep getting the error "Function definitions are not permitted in this context". Thanks in advance for your help. function [probingArray] = extractData (data, startValue, numberOfPeriods) arrayHeight=size(data,1); for i=1:arrayHeight if Date(i)==startValue datePosition=i; end end n=1; for i=(datePosition-numberOfPeriods):datePosition probingArray(n,1)=n; probingArray(n,2)=UK(i); n=n+1; end clear n i;
make sure you respect matlab conventions function [out1, out2, ...] = myfun(in1, in2, ...) declares the function myfun, and its inputs and outputs. The function declaration must be the first executable line of any MATLAB function. from http://www.mathworks.com/help/techdoc/ref/function.html