Retrieve a variable after simulating some data - matlab

I have a simulink model which I am running through a function , all the values to the blocks are assigned from within the function using assignin() function , now I want to retrieve the resulting data which is which is automatically saved in the workspace after simulation(I am using 'To workspace' block which stores the simulated result in a vector) , now I want to retrieve this data right after the simulation with the function. I used evalin() to retrieve the data from the workspace but it doesn't seem to work as it says the variable is undefined

I found the solution to the problem , Before I simulate the data I should enable the signal logging for the output first , then assign the simulation output to a variable as an object
FO =sim(filename,time);
after that I can retrieve the data variable to which the singal was logged from the simulation object
FT = FO.get('FT');
this works even with in a function unlike the 'To workspace' block

Related

Replace "eval" in vectors created inside a loop in MATLAB

I created a GUI that requests info from the user, which is then saved into series of variables (e.g. Fp1, Sn1, Fp2, Sn2, Fp3, Sn3...) and into different files (Info1.mat, Info2.mat, Info3.mat...). Once I have collected all of them, there's a vector created inside a loop with the value of each one of them. For example:
Fp1=0.8;
Fp2=0.9;
Fp3=0.85;
and I want to get:
Fp=[0.8 0.9 0.85];
I have already tried the following code:
for jj=1:1:ng
Fp(jj)=eval(sprintf('Fp%d',jj));
end
which is working fine, but I would like to know if there are other suggestions to do the same without "eval".

matlab UpdatePreviewWindowFcn

Im using GUIDE to make a matlab GUI which does some video computation.
Using the preview function I can preview the live video from my webcam and do some calculations.
In the MainGUI i use the:
setappdata(hImage,'UpdatePreviewWindowFcn',mypreview_fcn);
to get to a custom preview function which is:
function mypreview_fcn(obj,event,himage)
originalframe=peekdata(vidobj,1);
while isempty(originalframe)
originalframe=peekdata(vidobj,1);
end
if kk>=1
[LogResult,y,dist]=QueryArduino;
if LogResult==1
kk=kk+1;
results{kk,1}=originalframe;
results{kk,2}=measure1;
results{kk,3}=measure2;
results{kk,4}=measure3;
results{kk,5}=measure4;
results{kk,6}=measure5;
results{kk,7}=measure7;
offset=median([results{:,7}]);
offset=measure2-measure3;
end
end
set(himage,'CData',originalframe);
end
I would like to pass the result matrix to a table in the MainGUI
How can I access the GUI table;
You could do it using getappdata to pass all the data you want inside MainGUI and populate the table. Actually I don't understand why you would use setappdata to call a function.
For instance, in the function mypreview_fcn you coudl write something like this right before the end of the function:
setappdata(0,'MyData',results);
and then in MainGUI use getappdata:
TableData = getappdata(0,'MyData');
set(HandletoTable,'Data',TableData);
An alternative (and better approach I think) to getappdata would be to assign an output argument to the function mypreview_fcn so that when you call it from mainGUI the variable results is recognized inside mainGUI and you can populate the table simply using
set(HandletoTable,'Data',results);
Is this what you meant?

set threshold as a function of autoThreshold

I have written a macro for ImageJ/FIJI to deconvolve my confocal microscopy images and run the "3D Object Counter" plugin. The macro successfully runs all required commands and saves all required data in the specified places.
However, I have found that the 3D-OC autothreshold (as shown in the plugin dialog box) is to stringent resulting in objects being lost or divided.
To remedy this I would like to reduce the autothreshold by a predetermined function something similar to what was done here (from:How to get threshold value used by auto threshold Plugin) which resulted in this code:
setAutoThreshold();
getThreshold(lower,upper);
v=setThreshold(lower,upper*0.5);
run("3D Objects Counter", "threshold="v" slice=10 min.=400 max.=20971520 objects statistics summary");
The idea was to call the AutoThreshold values, modify them and set them to a variable. However when these lines are run the following error is returned:
Number or numeric function expected in line 3.
v=<setThreshold>(lower,upper*0.5);
And if the variable is inserted directly into the threshold key for run(3D-OC) the following msg is encountered:
Numeric value expected in run() function
Key:"threshold"
Value or variable name:"setThreshold(lower,upper*0.5"
Any suggestions or help on how to designate the 3D-OC threshold value as a variable as described would be greatly appreciated (as would any work arounds of course :) ).
Cheers
Edit: After testing Jan's response below (which works perfectly), it appears I need to call the threshold set by the 3D-OC plugin. Anyone know how to do this?
The getThreshold(lower, upper) function returns the lower and upper threshold levels in the provided variables. There is no need to assign any value to a new variable, and as you observed, setThreshold does not have any return value.
Instead, you can use the value(s) returned from getThreshold and use them as parameters in the run method (in the correct way, by string concatenation, see here):
setAutoThreshold();
getThreshold(lower, v);
run("3D Objects Counter", "threshold=" + v + " slice=10 min.=400 max.=20971520 objects statistics summary");
Alternatively, you can use &v in the second parameter to avoid string concatenation in the last line (see the documentation for the run() macro function):
run("3D Objects Counter", "threshold=&v slice=10 min.=400 max.=20971520 objects statistics summary");
You might have to use the lower instead of the upper threshold value, depending on whether you count bright or dark objects.

Matlab saving without losing previous iteration's value

i'm trying to save values of iterations in a loop. After this function, they will execute other functions before coming to the next iteration. But the problem i'm facing is, it overwrites them and bcomes 000000. Only the last iteration values are seen. How can i fix it ? Is there a way not to use the same variable and save them ? i read about append but will have to use different var name n is not really nice to do so.
function DistanceMatrix(iteration,distance_row)
load('data.mat','oridata')
load('centroids.mat','centroids')
for i = distance_row:(distance_row+3)
for j=1:300 %no.genes
total=0;
for k=1:6
total=total+((oridata(j,k)- centroids(i,k))^2);
end
DistMatrix_Val(i,j)=sqrt(total);
end
end
save('DistanceMatrix.mat','DistMatrix_Val')
DistMatrix_Val;
GroupMatrix(iteration,distance_row)
end
This is the output. I WOULD LIKE TO STORE ALL ITERATION's value and not overwrite them. Can any1 help ?
OK. Use
load('DistanceMatrix.mat','DistMatrix_Val')
or
persistent DistMatrix_Val
just before the first load command you showed to us.
I think this is what you should do:
functon DistanceMatrix = DistanceMatrix(iteration,distance_row)
Rather than saving the variable at the end of the function, you return it.
After returning it you can include the variable in a bigger variable (for example a three dimensional Nx4x300 matrix)
If neccesary you can then save it at the end.

Matlab: How to remove the error of non-existent field

I am getting an error when running matlab code. Here I am trying to use one of the outputs of previous code as input to my new code.
??? Reference to non-existent field 'y1'.
Can anyone help me?
A good practice might be to check if the field exists before accessing it:
if isfield( s, 'y1' )
% s.y1 exists - you may access it
s.y1
else
% s.y1 does not exist - what are you going to do about it?
end
To take Edric's comment into account, another possible way is
try
% access y1
s.y1
catch em
% verify that the error indeed stems from non-existant field
if strcmp(em.identifier, 'MATLAB:nonExistentField')
fprintf(1, 'field y1 does not exist...\n');
else
throw( em ); % different error - handle by caller?
end
end
Have you used the command load to load data from file(s)?
if yes, this function overwrite your current variables, therefore, they become non-existent, so when you call, it instead of using:
load ('filename');
use:
f=load ('filename');
now, to refer to any variable inside the loaded file use f.varname, for
example if there is a network called net saved within the loaded data you may use it like:
a = f.net(fv);
I would first explain my situation and then give the solution.
I first save a variable op, it is a struct , its name is coef.mat;
I load this variable using coef = load( file_path, '-mat');
In a new function, I pass variable coef to it as a parameter, at here, the error Reference to non-existent field pops out.
My solution:
Just replace coef with coef.op, then pass it to the function, it will work.
So, I think the reason behind is that: the struct was saved as a variable, when you use load and want to acess the origin variable, you need point it out directly using dot(.) operation, you can directly open the variable in Matlab workspace and find out what it wraps inside the variable.
In your case, if your the outputs of previous code is a struct(It's my guess, but you haven't pointed out) and you saved it as MyStruct, you load it as MyInput = load(MyStruct), then when use it as function's parameter, it should be MyInput.y1.
Hops it would work!
At first load it on command window and observe the workspace window. You can see the structure name. It will work by accessing structure name. Example:
lm=load('data.mat');
disp(lm.SAMPLE.X);
Here SAMPLE is the structure name and X is a member of the structure