I have 2 .m files, for an example say "project_main.m" and "my_function.m"
When I run the program in Octave it works fine. However the only variables I can see in the workspace area are those created in project_main.m, I would like to examine variables created in my_function.m from the workspace area.
Example:
project_main.m:
close all;
clear all;
clc;
X = 1;
Y = 2;
%---call function in external .m file---
my_function(X, Y);
my_function.m:
function functionResults = my_function(iX, iY)
fprintf("X = %d, Y = %d\n", iX, iY);
Z = iX*iY;
fprintf("Z = %d\n", Z);
end
This will give me on the command window:
X = 1, Y = 2
Z = 2
>>
As expected. However in the workspace area I only see X and Y, not Z:
I know I can see Z on the command window, but how do I examine variables created in separate .m files from the workspace area?
You'll need a debugger. This documentation page seems like a good start. Either run your function line-by-line using the command window, or set breakpoints to return the current function workspace to the global one.
Basically: variables within functions are private to that function and only the ones you output are copied into your workspace. In your case that is nothing, since fprintf doesn't return the output, it merely prints to the command window.
Related
I'm trying to write a code in Image J that will:
Open all images in separate windows that contains "488" within a folder
Use look up tables to convert images to green and RGB color From ImageJ, the commands are: run("Green"); and run("RGB Color");
Adjust the brightness and contrast with defined values for Min and Max (same values for each image).
I know that the code for that is:
//run("Brightness/Contrast..."); setMinAndMax(value min, value max); run("Apply LUT");
Save each image in the same, original folder , in Tiff and with the same name but finishing with "processed".
I have no experience with Java and am very bad with coding. I tried to piece something together using code I found on stackoverflow and on the ImageJ website, but kept getting error codes. Any help is much appreciated!
I don't know if you still need it, but here is an example.
output_dir = "C:/Users/test/"
input_dir = "C:/Users/test/"
list = getFileList(input_dir);
listlength = list.length;
setBatchMode(true);
for (z = 0; z < listlength; z++){
if(endsWith(list[z], 'tif')==true ){
if(list[z].contains("488")){
title = list[z];
end = lengthOf(title)-4;
out_path = output_dir + substring(title,0,end) + "_processed.tif";
open(input_dir + title);
//add all the functions you want
run("Brightness/Contrast...");
setMinAndMax(1, 15);
run("Apply LUT");
saveAs("tif", "" + out_path + "");
close();
};
run("Close All");
}
}
setBatchMode(false);
I think it contains all the things you need. It opens all the images (in specific folder) that ends with tif and contains 488. I didn't completely understand what you want to do with each photo, so I just added your functions. But you probably won't have problems with adding more/different since you can get them with macro recorder.
And the code is written to open tif files. If you have tiff just be cerful that you change that and also change -4 to -5.
I'm creating a script for automated measuring fluorescence intensity. I have done some progress, the macro opens the image, split in as many channels as I have and perform some trasformation so that it is possible to execute particle analysis at image 1. Then, what I want is to measure all the created ROIs but I am stacked at this point:
here is my code
dir1 = getDirectory("Choose Source Directory ");
list = getFileList(dir1); // get the list of all filenames in the directory
subst = 3; // set the "subst" variable to 3
Dialog.create("BatchSplitStacks"); // create a dialogue to change the stack divisor
Dialog.addNumber("Number of substacks:", subst); // in the dialogue, get the number of substacks, default is "subst" (=3)
Dialog.show(); // show the above created dialogue
chan = Dialog.getNumber(); // the stack divisor is defined
setBatchMode(false); // do not show the images while processing them
for (i=0; i<list.length; i++) { // go through the files of the folder
showProgress(i+1, list.length); // the progress of the processing of the actual stack is shown in the ImageJ window
open(dir1+list[i]); // open an original stack
name = list[i]; // get the filename of the original stack
run("Stack Splitter", "number="+chan); // run the Stack Splitter plugin with the defined divisor
for (e=0; e<chan; e++) { // for each substack a saving routine is run
dotIndex = lastIndexOf(name, "."); // this line and the following line I took from another macro but I do not know
// substacks with a number below 10 are saved with a suffix and a 2 digit extension (e.g. 01 instead of the standard 1)
saveAs("tiff", dir1+"c0"+e+".tif");
close();
// closing substack
} // next saving routine
close(); // closing current original stack
open(dir1+"c02.tif");
run("Enhance Contrast", "saturated=0.35");
run("Enhance Contrast", "saturated=0.35");
run("Enhance Contrast", "saturated=0.35");
setAutoThreshold("Default");
setAutoThreshold("Default dark");
run("Make Binary");
run("Make Binary");
run("Watershed");
run("Analyze Particles...", "size=0.30-50.00 circularity=0.00-0.70 show=Masks display summarize add in_situ");
open(dir1+"c01.tif");
run("Subtract Background...", "rolling=50");
saveAs("Results", dir1+name+"c02"+ ".txt");
} // move on to next original stack in the folder
Thanks
You can measure all ROIs in the ROI Manager using the Measure button. In a macro, the lines are:
roiManager("Deselect");
roiManager("Measure");
You can learn more macro commands easily by using the Macro Recorder.
You can browse all the available macro functions online.
For more sophisticated per-ROI analysis, you can loop over the ROIs in the manager using the roiManager("count") and roiManager("select", i) commands. The Scale_All_ROIs macro gives an example of this; you can easily load that macro into the Script Editor by opening a new script (File > New > Script) and then choosing it from the Templates > IJ1 Macro menu of the Script Editor.
I've just installed the new MATLAB R2013b for 64bit Mac, and my OS is OS X 10.8.4. I'm running into a consistent problem that I never had with R2013a. When I run one of my scripts (see below), the entire script goes through OK, but then I keep getting an error message "MATLAB has encountered an internal problem and needs to close." Then I have to shut MATLAB down.
I have a feeling that I've goofed somewhere on the installation since I'm new to MATLAB, but I'm not sure.
This exact same script still runs fine on R2013a, which I've yet to uninstall. The script (making use of Psychtoolbox) is an experiment which opens a screen, presents some text, presents an audio file, and requires the participant to respond with 6 keystrokes. This script only presents two audio files, since I'm just testing it.
All the loops seem to work on both versions of MATLAB, and the screen closes at the end (which only happens after 2 passes through the main loop). I take this to mean the script is working, but something in a post stage is causing issues.
Any and all ideas are much appreciated!
-Josh
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% SCREEN & AUDIO SETUP %%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%
%% SCREEN %%
%%%%%%%%%%%%
% Set up a nice blank screen.
whichScreen = 0;
% Full Screen mode
%window = Screen(whichScreen, 'OpenWindow');
% Small screen mode used for code testing
window = Screen('OpenWindow',0, [450 450 500], [5,5, 550,550]);
white = WhiteIndex(window); % pixel value for white
Screen(window, 'FillRect', white);
Screen(window, 'Flip');
% Set global text size for the display.
Screen('TextSize', window, 15);
Screen(window,'TextFont','Arial');
Screen('TextStyle', window, 0)
%%%%%%%%%%%
%% AUDIO %%
%%%%%%%%%%%
% Set initial audio parameters:
nrchannels = 1; % All stimuli are mono-sounds.
freq = 44100;
% Initialize sound driver.
InitializePsychSound;
try
pahandle = PsychPortAudio('Open', [], [], 3, freq, nrchannels);
catch
% If the above fails, use the audio device's standard frequency.
psychlasterror('reset'); % I believe this some reseting of the error made in 'try'.
pahandle = PsychPortAudio('Open', [], [], 3, [], nrchannels);
end
%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%
%%%%% MAIN LOOP %%%%%
%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%
home = '/Users/josh/Dropbox/Beverlab/Fall_2013_Study/Design/Matlab/'
SampleExperiment = {strcat(home,'Stimuli/tokensA/gipa_mono.wav'),...
strcat(home,'Stimuli/tokensB/gabo_mono.wav')};
timeLimit = 10; % Set up the time limit.
ans = 0; % This is used to track whether or not the participant answered.
numStim = 2; % Just using 2 right now to test the code
ListenChar(0);
for i=1:numStim;
token = char(SampleExperiment(1,randi([1,2]))); % randomly select a wave file from 'SampleExperiment' and assign it to 'token'
[y,freq] = wavread(token); % Read the current wav file.
wavedata = y'; % Transpose wav data.
PsychPortAudio('FillBuffer', pahandle, wavedata); % fill the buffer, ready to play
t1 = PsychPortAudio('Start', pahandle, 1, 0, 1); % play the wave file and get timestamp in one go
while GetSecs<t1+timeLimit
if ans<6
[secs, keyCode, deltaSecs] = KbWait([],2,t1+timeLimit);
if isempty(find(keyCode,1))
break
end
if ~isempty(find(keyCode,1))
ans=ans+1;
end
end
if ans==6
WaitSecs(rand*3+1);
break
end
end
if ans<6
DrawFormattedText(window, 'Lets try that again...press 6 times', 'center', 'center');
Screen(window, 'Flip');
WaitSecs(1);
Screen(window, 'FillRect', white);
Screen(window, 'Flip');
[y,freq] = wavread(token); % Read the current wav file.
wavedata = y'; % Transpose wav data.
PsychPortAudio('FillBuffer', pahandle, wavedata); % fill the buffer, ready to play
t1 = PsychPortAudio('Start', pahandle, 1, 0, 1); % play the wave file and get timestamp in one go
while GetSecs<t1+timeLimit
if ans<6
[secs, keyCode, deltaSecs] = KbWait([],2,t1+timeLimit);
if isempty(find(keyCode,1))
break
end
if ~isempty(find(keyCode,1))
ans=ans+1;
end
end
if ans==6
WaitSecs(rand*3+1);
break
end
end
end
end
Screen('CloseAll')
This sort of error usually indicates something drastic and unrecoverable has happened. It appears that the Psychtoolbox contains MEX files, that is probably the most likely culprit. I would either attempt to rebuild those using R2013b, or contact the authors to see if they have a version compatible with R2013b.
This crashing is likely due to a new bug in OSX 10.8.4, causing PsychToolBox to crash on closing the connection to the display server (and apparently bringing MATLAB with it). See here for discussion and resolution.
Anybody still having this issue, please update to the latest version of PsychToolBox (which is always a good idea!)
I am encountering an odd problem. I am able to create and save pdf file using R/ggplot2 and view them while the R Console is running. As soon as I exit the R console, Preview on Mac OS X will no longer display the PDF. I have been able to save .png files w/o problem, but for reasons beyond my control, I need to save in pdf files. The code I am using to save is as follows:
pdfFile <-c("/Users/adam/mock/dir/structure.pdf")
pdf(pdfFile)
ggplot(y=count,data=allCombined, aes(x=sequenceName, fill=factor(subClass))) + geom_bar()
ggsave(pdfFile)
Has anyone encountered a similar problem? If so, what do I need to do to fix it?
Thank you very much for your time.
The problem is that you don't close the pdf() device with dev.off()
dat <- data.frame(A = 1:10, B = runif(10))
require(ggplot2)
pdf("ggplot1.pdf")
ggplot(dat, aes(x = A, y = B)) + geom_point()
dev.off()
That works, as does:
ggplot(dat, aes(x = A, y = B)) + geom_point()
ggsave("ggplot1.pdf")
But don't mix the two.
It is in the R FAQ, you need a print() around your call to ggplot() -- and you need to close the plotting device with dev.off() as well, ie try
pdfFile <-c("/Users/adam/mock/dir/structure.pdf")
pdf(pdfFile)
ggplot(y=count,data=allCombined,aes(x=sequenceName,fill=factor(subClass)))
+ geom_bar()
dev.off()
Edit: I was half-right on the dev.off(), apparently the print() isn;t needed. Gavin's answer has more.
The following plot
pdf("test.pdf")
p <- qplot(hp, mpg, data=mtcars, color=am,
xlab="Horsepower", ylab="Miles per Gallon", geom="point")
p
dev.off()
works in the console but not in a function or when you source this from a file.
myfunc <- function() {
p <- qplot(hp, mpg, data=mtcars, color=am,
xlab="Horsepower", ylab="Miles per Gallon", geom="point")
p
}
pdf("test.pdf")
myfunc()
dev.off()
Will produce a corrupt pdf file and the way to fix it us use
print(p)
within a function.
In a console. "p" is automatically printed but not in a function or when you source the file.
You can also change the filename of your pdf plot within ggsave if you want to call it something other than "ggplot1" or whatever concise object name you chose; just give the filename first and then tell it which plot you're referring to, for example:
a <- ggplot(dat, aes(x = A, y = B)) + geom_point()
ggsave("Structure.pdf",plot=a)
I have such code:
a=5;
b=a;
c=10;
u = (0:0.05*pi:2*pi)'; %'
v = [0:0.05*pi:2*pi];
X = a*sin(u)*cos(v);
Y = a*sin(u)*sin(v);
Z = c*cos(u)*ones(size(v));
Z(Z>0)=0; % cut upper
V1=4/3*pi*a*b*c;
d=1/2;
e=2^d;
a2=a/e;
b2=a/e;
c2=c;
V2=4/3*pi*a2*b2*c2;
X2 = a2*sin(u)*cos(v);%-2.5;
Y2 = b2*sin(u)*sin(v);
Z2 = c2*cos(u)*ones(size(v));%+0.25;
Z2(Z2>0)=0; % cut
h=1/3;
for j = 1:20
k1=(sin(pi*j/20)+0.5)^h;
a=a*k1;
c=c*k1;
X = a*sin(u)*cos(v);
Y = a*sin(u)*sin(v);
Z = c*cos(u)*ones(size(v));
Z(Z>0)=0;
a2=a2*k1;
b2=a2*k1;
c2=c2*k1;
X2 = a2*sin(u)*cos(v)+5;%-2.5;
Y2 = b2*sin(u)*sin(v);
Z2 = c2*cos(u)*ones(size(v));%+0.25;
Z2(Z2>0)=0;
hS1=surf(X,Y,Z);
alpha(.11)
hold on
hS2=surf(X2,Y2,Z2);
hold off
axis([-20 20 -20 20 -20 20]);
F(j) = getframe;
end
movie(F,4)
I have to input parameters a,b,c from the keyboard. I've made GUI & tried to do it by using "Edit text" with a function below, but it's not working((.
I can't understand what's the problem with it.
function a_edit_Callback(hObject, eventdata, handles)
user_entry = str2double(get(hObject,'string'));...
a=user_entry;
The problem is that your callback function executing your code is not 'seeing' the parameters you defined in your edit text callbacks. You need to establish your variables in the subfunction, since they aren't global.
Using guide, set up a uicontrol button to click when you've entered your parameters into your uicontrol edit text boxes. Under the callback of your button, place your above code, with the following at the top:
a=str2double(get(handles.a_edit,'String'));
b=str2double(get(handles.b_edit,'String'));
c=str2double(get(handles.c_edit,'String'));
This will pull in the current strings of your edit text uicontrols. (Assuming you've assigned the tag format x_edit for each of the edit text boxes in guide.)
EDIT:
Open the figure you already created with the edit text boxes. Next, check to make sure each of your text boxes have the tag a_edit, b_edit, c_edit by using the property inspector. Then create a button using guide, and open the property inspector by double clicking on it. Find the 'tag' field, and name it run. Save your figure, and open the corresponding M-file.
Next, find the line with run_Callback(hObject, eventdata, handles). Place the following under it:
a=str2double(get(handles.a_edit,'String'));
b=str2double(get(handles.b_edit,'String'));
c=str2double(get(handles.c_edit,'String'));
%# Add the rest of your code from above verbatim, minus the first three lines
This should be the ONLY code you add to the auto-generated M-file - don't mess with anything else until you get this much working. If you don't want the animation popping up randomly in your figure window, you can add a set of axes using guide as well.
From the looks of the code, it appears to be a 'script' and not a 'function'.
Did you just want a 'dialog (built-in GUI dialog)'? If so, you can add the following at the beginning of your script:
prompt = {'Enter the parameter value "a":','Enter the parameter value
"b":','Enter the parameter value "c":'};
dlg_title = 'Input the Parameter Values';
num_lines = 1;
def = {'5','5','10'};
answer = inputdlg(prompt,dlg_title,num_lines,def);
a=answer{1};a=str2double(a);
b=answer{2};b=str2double(b);
c=answer{3};c=str2double(c);
% Y.T.