Cast entire matlab workspace to some class - matlab

I'm looking for a way to cast the entire workspace in matlab to some class (say double).
For simplicity, lets just assume that only "simple" classes are present in the workspace (no cells or structs). Of course I can go line by line and change each variable, x=double(x) , but that's not practical if I have several 100's of variables. This is what I've wrote so far:
% # generate some variables of different classes
a1=int32(120);
a2=single(rand(10));
a3=double(rand(20));
a4=(rand(5)>0.5); %# logical
% # collect workspace variables using `whos`
ws=whos;
for ii=1:size(ws,1)
[ ? ] = double(eval(ws(ii).name))
end
The last line double(eval(ws{1,ii})) performs the casting, but how should I assign it's output automatically to the original variables names?
You are also welcome to suggest an alternative way to cast all variables of the workspace, if you can think of one...

Interesting question (+1). What about this?
ws = whos; %# Obtain workspace
for n = 1:size(ws,1)
eval([ws(n).name, ' = double(', ws(n).name, ');']); %# Assign to double
end
This worked for me on R2012b. The trick is to alter the variable type and assign it with one call to eval.

Related

When does the workspace change in MATLAB?

I have a couple questions regarding MATLAB workspaces:
When does MATLAB decide to change the workspace and what conditions prompt it?
Something strange is happening in the following example. I run it with a breakpoint at line 4, then step using F10 to watch the workspace variables. Clearly, I see that m is deleted within the first iteration of the inner loop, but somehow MATLAB still knows to go to the next iteration in the outer loop!
Example:
something = 2;
somethingelse = 3;
for m = 1 : something
for n = 1 : somethingelse
%do something
clearvars -except n something somethingelse % This clears m, but it still functions
end
end
The only thing I can think of is that MATLAB probably has not updated the memory locations given that the variable does not show on the list.
In MATLAB there are generally two types of workspaces: the base workspace and function workspaces. The base workspace is what you use when you enter commands at the command line, or when you run scripts (all of which share the base workspace). Conversely, each function has its own unique workspace. Unlike C or C++ (or a number of other languages) you don't have any scoping of variable within loops or conditional structures, just one unique workspace for each instance of a function.
The issue you're seeing in your example isn't really related to this, it's just an artifact of how for loops behave in MATLAB. Taken from the "Tips" section:
Avoid assigning a value to the index variable within the loop statements. The for statement overrides any changes made to index within the loop.
In other words, once an iteration of the loop completes and returns to the beginning, MATLAB ignores any changes to the loop variable and simply increments it to the next value.
If you'd like to learn more details about MATLAB workspaces and scoping, I'd check out these links:
Share Data Between Workspaces
Nested functions
Local functions
global variables
persistent variables
Function handles
Matlab changes workspace to the current scope.
You've only cleared the value of m within the scope of the second loop.
Try adding p = m+n after the clearvars command within the second loop. Since you've cleared m only within the scope of the n loop, you cannot use it. However, you did not remove m from the scope of the m loop.
Also, since the m for loop exists within the scope of your base workspace, you can clear m within the m for loop all you want, the loop will always have access to it. That's why, if you remove the clearvars line, when you return to the base workspace, you can see m and n equal to something and somethingelse respectively.
What I think you're looking for is a better explanation of Matlab's memory management, which you can find here: MATLAB's Garbage Collector?

convert struct type to matrix octave

I have a myfile.mat that contains 3000x35 size data. When I load it into a variable as :
a = load('myfile.mat')
It gives struct of size 1x1 . How can I get exact form as matrix. This is required because I need to change certain column values.
(This answer is valid for MATLAB, I am not sure it works exactly the same way in Octave)
You have several options:
Option 1:
If the .mat file only contains one variable, you can do:
a = struct2array(load('myfile.mat')); % MATLAB syntax
a = [struct2cell(load('myfile.mat')){:}]; % Octave syntax
Option 2:
You need to know the name of the variable at the time of saving, which is now a name of a field in this struct. Then you would access it using:
a = load('myfile.mat'); a = a.data;
Option 3 (unrecommended!):
Just remove the a = part of the expression,
load('myfile.mat');
Then the variables inside this file will "magically spawn" in your workspace. This is not recommended because it makes it difficult (impossible?) to see when certain variables are created.
I found the solution myself. I did like this
a = load('myfile.mat')
a = a.data
So that now I can access values of a as matrix with indexing, a(1,2) like this.
It is in octave. I hope it is similar in matlab.

Saving variables within a function? (MATLAB)

I have a function that goes something like this:
function [] = function1
-variable1= value1;
-variable2= value2;
-matrix1=[]
-matrix2=[]
-loops that fill in matrix1 and matrix2
-more declarations
-final function1 end
function2[]
takes values from function 1 and does stuff, creates new variables
funcion2 end
function3[] that uses values from function 2 and function4[] that uses function 3.
(Sorry for all of that by the way). Now, my question is, is there anyway to save variables, arrays, etc. in the workspace for later analysis? All 4 functions are on the same tab in the MATLAB editor.
To save any particular variable from workspace in Matlab you should execute the following
save('Name of the mat file','Name of the variable')
To save multiple variable the command shall be
save('name of the mat file','var1','var2'...)
variable can be array, matrix, structure, double anything. For any other use of the function save please docsearch it in the command prompt

Matlab: assign variable only if not already existing?

This is the matlab equivalent to this question. Essentially, I'm wondering if there is a way to avoid explicitly writing the exists check for a variable before assigning it.
You may use
persistent varname
if isempty(varname)
varname=heavyComputation()
end
This will only recompute varname at startup and after each clear fun and clear all.
Why avoid exist? This is exactly what it is for:
if ~exist('t', 'var')
t = 1
end
For your specific use case, if you don't want a certain variable to be recalculated, save it into a MAT-file and check for its existence before recalculating. For example, if you are calculating A, then you can do something along the lines of:
if exist('mycalcs.mat', 'file')
load('mycalcs.mat', 'A') %// Load precalculated A
else
A = do_some_calculations(); %// Calculate A
save('mycalcs.mat', 'A'); %// Save it to a workspace file
end
This allows you to rerun the script without repeating calculations, even after clearing the variable in question or closing MATLAB altogether.
You could use the syntax who(variable_name) to check if the variable exists in the workspace as shown here: http://www.mathworks.com/help/matlab/ref/who.html

Matlab, automatically delete the index variable after the execution of a loop

On Matlab, when i am using a "for...end" loop, the indexing variable still exists in my workspace after the loop have been fully executed. I would like it to be automatically deleted, since its not relevant anymore outside of the loop and that it pollutes the workspace.
For example, in the following code, the variable "i", still exists after the execution of the loop. Since it should be a local variable, I would like it to be deleted automatically without me having to do it explicitely.
List = [1 2 3 4] ;
for i = List
fprintf('value = %i\n', i) ;
end
% "i" still exists, while its outside of its context
clear i; % I would like to avoid doing this everytime I exit a for..end
I know it is more of an aesthetic issue than a bug, but for an easier understanding of the results of my program, I would like those "temporary" variables to disappear when I exit their contexts.
So far, I only was able to reduce the number of those temporary variables by reusing them.
Edit:
It seems that there is no real solution to automatically remove those "temporary" variables.
The closest ways to avoid having those variables are:
Avoiding loops
Make the loops in functions, the variables of the functions are local and won't get in the workspace.
If you REALLY want to make sure that some of your variables have limited scope, and you want to avoid calling clear, you can use nested functions. Note that this may not help with readability, and it is more typing than calling clear. However, it does make sure that the only variables in your main function workspace are the ones that you want/need to remain.
function doSomething
List = [1 2 3 4] ;
runLoopOnList()
%# some other code here
%# nested functions
function runLoopOnList
%# i, and any other variable defined here
%# will not appear in the workspace
%# in contrast, all variables in the workspace
%# are visible and can be changed by the nested function
%# If a nested function should assign a new important
%# variable in the main workspace, have it return
%# and output.
for i = List
fprintf('value = %i\n', i) ;
end
end %# nested function
end %# main function
Look ! No loop, no iteration variable !
fprintf('value = %i\n', List)
And, while I'm here, I disagree that your i is a temporary variable; you've put it in the workspace so it is, essentially, global. Put it in another context (e.g. inside a function) if you don't want it to 'pollute' the workspace.
And yes, I know that Matlab has a concept of global variables which is slightly different from workspace variables, but it's not quite relevant here.