This question already has answers here:
Is it possible to have a workspace variable that persists across a call to clear?
(2 answers)
Closed 9 years ago.
Does MATLAB keep some variables after clearing?
Matlab: Free memory is lost after calling a function
My question is related to this post but some changes are there.
I have to use the output (the outputs are matrices generated, i.e. i am generating small matrices in every iteration) produced by previous large program, in my next iteration of large program, so when i am using the technique mentioned in the post, i am getting error that " Reference to a cleared variable", i need to keep some of the variables and some matrices generated. How to do that?
Sometimes the error occurs after 1 iteration only
Thanks
You can clear specific variables in the workspace with:
clear myvarname
You can also clear functions that might be holding persistent variables with:
clear myfunname
So - you should work out which ones you don't want (type whos to see variables in the workspace, or in a breakpoint) and clear the ones you don't need.
Another option would be to save the ones you do want, use the clear method you mentioned, then re-load.
Related
This question already has answers here:
Subscript indices must either be real positive integers or logicals, generic solution
(3 answers)
Closed 3 years ago.
I have just recently started using MATLAB as it's pretty good for machine learning and the like.
Currently, I am working on some type of classification which is pretty long-winded and complicated if I tried to explain everything I am trying to accomplish therefore I will just state the exact code giving me problems.
So, I am given a 1010 x 1764 single type matrix by some function. say the matrix is called train_examples_2_2 as you can see on the right-hand side of the screenshot below.
As you can also see from the screenshot above (on the right-hand side), the calls to mean and std:
mean = mean(train_examples_2_2)
std = std(train_examples_2_2)
Yield the correct results.
However, when I run the same code several times sometimes I get an error on the line mean = mean(train_examples_2_2) stating:
Array indices must be positive integers or logical values.
The exact code I am concerned with is:
mean = mean(train_examples_2_2) % <----- error appears here
std = std(train_examples_2_2)
for i=1:size(train_examples_2_2,1)
train_examples_2_2(i,:) = train_examples_2_2(i,:) - mean;
train_examples_2_2(i,:) = train_examples_2_2(i,:) ./ std;
end
% end of standardisation process
where train_examples_2_2 is provided by some function that I did not create nor can modify.
According to the MATLAB documentation:
If A is a matrix, then mean(A) returns a row vector containing the
mean of each column.
which is what I get the first time I run the code upon opening Matlab but after that, it yields the aforementioned error.
I am using MATLAB R2018b.
I'm I making a simple mistake or could this possibly be a bug?
Thanks for taking the time to help out.
unlike let's say python you shouldn't/can't/mussn't re-define function names or default variables.
mean = mean(train_examples_2_2) % <----- error appears here
matlab doesn't distinguish between the callable mean() function and the variable ```mean``. especially confusing since indexing and calling sth is done by using round brackets.
So....?
call your variable sth. other than mean. mean_ will already do the trick.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I want to get the content of a variable from its name as a string:
%suppose that I have structures variables in the workspace:
struct_1=struct('field1' ,"str",'field2',0:5)
struct_2=struct('field1' ,"str",'field2',0:10)
struct_3=struct('field1' ,"str",'field2',0:20)
%and I have an other variable like:
a=5
var2='hello'
%and I want to concatenate all these structures in the same structure
%So i wan to get their name.
%I don't know if there is an other way to get just the structure variables
structures=who(str*)
array=[]
for i=1:length(structures)
array=[array; structures(i). field2]; % here I get an error because the content of structures are string representing the variable name
end
%create the new struct
str='newstr_value'
struct_4=struct('field1',str, 'field2',array)
How to fix this error and is there any way to do this better ?
While I would still highly recommend going back to the point of origin of these dynamically named structures (shame ššš on the toolbox creator if this is actually the output...) and fixing this problem there, there is an approach that does not require the use of eval.
Similar to my approach for a tangentially related question, you can save the desired structures to a temporary *.mat file and take advantage of load's optional structure output to consolidate the data structures for access in a more robust programmatic matter.
For example:
struct_1=struct('field1' ,"str",'field2',0:5);
struct_2=struct('field1' ,"str",'field2',0:10);
struct_3=struct('field1' ,"str",'field2',0:20);
save('tmp.mat', '-regexp', '^struct_');
clear
oldworkspace = load('tmp.mat');
varnames = fieldnames(oldworkspace);
nvars = numel(varnames);
% Get original structure fields
% The subsequent steps assume that all input structs have the same fields
fields = fieldnames(oldworkspace.(varnames{1}));
nfields = numel(fields);
% Initialize output struct
for ii = 1:nfields
newstruct.(fields{ii}) = [];
end
newstruct(nvars) = newstruct;
for ii = 1:nvars
for jj = 1:nfields
newstruct(ii).(fields{jj}) = oldworkspace.(varnames{ii}).(fields{jj});
end
end
Gives us:
Yay.
Not sure if your situation absolutely requires dynamic calls of variables by their string names. eval can solve your problem. However, eval is slow. At times, it is unreliable. You can easily have conflicting code as you build various components of your project. And in my experience, there have always been alternatives to eval. In your case, Adriaan outlined an example in his comment.
Since you are only trying to interface with a third-party toolbox, if the number of variables you read is reasonable, you can do the followings with eval.
array=struct;
for i=1:length(structures)
eval(['array(',num2str(i),').field2=',structures{i},';'])
end
If you know all the structs are named struct_#, you can also do
array=struct;
num=3; % the number of outputs from your toolbox
for i=1:num
eval(['array(',num2str(i),').field2=struct_',num2str(i),'.field2;'])
end
Note that your field2 values are all arrays. You can't just create an array and expect each "cell" to carry another array value. Arrays, or rather matrices, in Matlab are a special data type. They only take numerical values. (Matrices are highly optimized in Matlab in various ways. That is why we use Matlab.)
Also note that when you set equality of fields of structs, the equality is by reference. There is no deep copy of the data. Modifying one will modify another. (Just beware of this but don't necessarily rely on it. Deciding when to deep copy things is one of the things we let Matlab handle.)
As well, be careful with the result from who. You need to be absolutely clear with what is in the local scope. Above is assuming your result from calling structures=who(str*) is correct for your application.
This question already has answers here:
Get actual line being executed in Matlab code
(2 answers)
Closed 6 years ago.
Suppose main.m calls func1.m, and func1.m calls func2.m in three parts of func1.m
Suppose I am printing some variables in func2.m because there was some error.
So suppose I printed
var2 = 3
var2 = 5
var2 = -1
I am just talking about an example. But if the program is very complex, then since func1.m is calling func2.m at three points, I can get confused as to which part of func1.m is generating var2=3 at func2.m
So if I can print the "line number" of current line (including the line number of upper-level function), then it will be very useful for debugging.
Is there such thing?
You can use dbstack to figure out what line of the calling function called this. You could look for func1 specifically in the call stack.
stack = dbstack();
[~, ind] = ismember({stack.name}, 'func1');
disp(stack(ind).line)
That being said, it is far better to set a conditional break point and then use dbup and dbdown or the MATLAB workspace browser to navigate to parent and child workspaces to figure out what went wrong.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I detect if Iām running MATLAB or Octave?
My code was designed using MATLAB and I still use it. However, if I try to run some parts of it using Octave, I get errors. For example, MATLAB code uses pause on which Octave doesn't.
Is there a way to check which programming environment is using the code? For example,
if invoking_env == 'Matlab'
% do this
else
% ok, so do this
end
I can use getenv('COMPUTERNAME') but in this case the computer name is the same! Thanks.
There is version function both in MATLAB and Octave. They return different values and MATLAB's version have some arguments, that are absent in Octave. Hope that helps.
I think the best method is to have a sub function that checks this. The following snippet is probably the one that requires the minimum from the system. And with the persistent variable it can be called repeatedly without a heavy performance hit.
function r = isoctave ()
persistent x;
if (isempty (x))
x = exist ('OCTAVE_VERSION', 'builtin');
end
r = x;
end
You can then use it easily in condition blocks. See that entry on the Octave wiki.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I get the handles of all open figures in MATLAB
The situation is following. I run a couple of tests, which plot a lot of figures. I would like to convert them to pdf and compile into one file. Since each time I may get different type of plots and different number of plots, I need to get the list of all figures in current matlab session or workspace. Is this doable?
Thanks
h = get(0,'Children');
will put the "handles" to the figures you currently have in the variable h. get(handle) and set(handle,...) are gigantically useful in general. The handle 0 points at the root of the display, so all the figures on the display are the root's Children.