Rename a table via the auto-generated import data script - matlab

I use the auto-generated script by Matlab to import a text file. However I am wondering following unsuccessful attempts (so far) if there exist efficient ways to rename the default table name (out) using a concatenation of the subco_ variable as illustrated below:
subco_={12345,23456,34567,45678};
['N',num2str(subco_{1,3})] % leading to N34567 (of char type)
Having performed slight modifications into the section (from Matlab auto-generated script)
%% Create output variable
out = table
out.columnames = rawCellColums(:,x) x=1...
I naturally end up in my workspace with the table called out (so far nothing special), however I'd like to rename:
['N',num2str(subcode_{1,3})] = out
Error: An array for multiple LHS assignment cannot contain LEX_TS_STRING.
I understand that the assignment could not merely be performed in such a way for 2 data of different data types (different dimensions, etc.) array2table() being helpless.
As a way around, I have 2 trivial options:
right-click on out (in the workspace), and rename the latter variable to N34567,
create manually N43456 as a variable and assign it to out(in script); N34567= out
However the above way-around involve a manual intervention that I'd like to get rid off. Thus any idea on the assignment of elements to subco_ would be appreciated.

Related

Collect internal variables of nested functions in matlab

I have a project consisting of multiple nested functions.
For debugging purpose I want to save all internal variables in one way or another, in order to display figures, replay parts of code etc...
I also want to keep this as transparent as possible regarding calculation time.
My first thought was to create a global variable, and store programmatically at the end of each function the inputs and outputs inside the variable as a structure :
globalVariable.nameOfParentfunction_NameOfFunction.nameInput1 = valueInput1;
globalVariable.nameOfParentfunction_NameOfFunction.nameInput2 = valueInput2;
...
globalVariable.nameOfParentfunction_NameOfFunction.nameOutput1 = valueOutput1;
...
Is it possible to use some kind of reflection to get the name and value of inputs/outputs without necessarily parse the file where the function is written?
I found a good but maybe outdated topic about parsing
How do I collect internal signals?
The simple solution is to use save, which will save all variables in the current workspace (the function’s context) to file.
If you want to keep the values in memory, not in a file, you can use names = who to get a list of all variables defined in the current workspace, then use val = eval(names{i}) to get the value of the variable called name{i}.
I would recommend putting all of that in a separate function, which you can call from any other function to store its variables, to avoid repeating code. This function would use evalin('caller',…) to get names and values of variables in the workspace of the calling function.
Note that using eval or evalin prevents MATLAB from optimizing code using its JIT. They also are dangerous to use, since they can execute arbitrary code, however in this case you control what is being executed so that is no a concern.

How do I best resolve this MATLAB name conflict?

I have saved some data in MATLAB data files, where the variable name of each of the files is times. When I now try to read those data files, it seems to create a name conflict with (I think) the built-in function times.
The lines:
load("matlabcode\eeglab2020_0//timesBxintIlow.mat","times");
times1=times;
lead to the error:
Error using .*
Not enough input arguments.
The error actually doesn't appear when I type it into the MATLAB console, but only when I call the function that uses the 2 lines from the console)
Can I change the name of my variable "times" somehow?
I have tried locating the built-in function:
which times
built-in (C:\Program Files\MATLAB\R2019b\toolbox\matlab\ops\#char\times) % char method
I don't know what the #char means, but times seems to be in the folder ops. However, changing the name of this file times doesn't change the error message. The plan was to programmatically change the name to times_renamed, then load the data and then change the name back.
I also could not figure out how to remove the built-in function from the search path.
Load your data into a structure array as follows:
S = load("matlabcode\eeglab2020_0//timesBxintIlow.mat", "times");
Now you'll be having your required data in S.times instead of times variable.

Exploit Matlab copy-on-write by ensuring function arguments are read-only?

Background
I'm planning to create a large number of Matlab table objects once, so that I can quickly refer to their contents repeatedly. My understanding is that each table variable/column is treated in copy-on-write manner. That is, if a table column is not modified by a function, then a new copy is not created.
From what I recall of C++ as of 1.5 decades ago, I could ensure that the code for a function does not modify its argument's data by using constant-correctness formalism.
The specific question
I am not using C++ in these days, but I would like to achieve a similar effect of ensuring that the code for my Matlab function doesn't change the data for selected arguments, either inadvertently or otherwise. Does anyone know of a nonburensome way to do this, or just as importantly, whether this is an unrealistic expectation?
I am using R2015b.
P.S. I've web searched and came across various relevant articles, e.g.:
http://www.mathworks.com/matlabcentral/answers/359410-is-it-possible-to-avoid-copy-on-write-behavior-in-functions-yet
http://blogs.mathworks.com/loren/2007/03/22/in-place-operations-on-data
(which I need clarification on to fully understand, but it isn't my priority just now)
However, I don't believe that I am prematurely optimizing. I know that I don't want to modify the tables. I just need a way to enforce that without having to go through contortions like creating a wrapper class.
I've posted this at:
* Stack Overflow
* Google groups
There is no way of making variables constants in MATLAB, except by creating a class with a constant (and static?) member variable. But even then you can do:
t = const_table_class.table;
t(1,1) = 0; % Created and modified a copy!
The reason that a function does not need to mark its inputs as const is because arguments are always passed by value. So a local modification does not modify data in the caller’s workspace. const is something that just doesn’t exist in the MATLAB language.
On the other hand, you can be certain that your data will not be modified by any of the functions you call. Thus, as long as the function that owns the tables does not modify them, they will remain constant. Any function you pass these tables to, if they attempt to modify them, they will create a local copy to be modified. This is only locally a problem. The memory used up by this copy will be freed upon function exit. It will be a bug in the function, but not affect code outside this function.
You can define a handle class that contains a table as it's preperty. Define a property set listener that triggers and generates error/warning when the value of the property changes.
classdef WarningTable < handle
properties (SetObservable)
t
end
methods
function obj = WarningTable(varargin)
obj.t = table(varargin);
addlistener(obj,'t','PreSet',...
#(a,b)warning('table changed!'));
end
end
end
This should generate warning:
mytable = WarningTable;
mytable.t(1,1) = 0;

automatically get the name vectors saved in the workspace in Matlab

I have multiple vectors (+100) that have been loaded into MATLAB workspace, I would like to write a script that can plot and save them all, but for that I need their name, my question is: is there a way to automatically get the name vectors saved in the workspace.
thanks in advance.
Step one: whoever gave you a *.mat file with 100+ named variables in it, [censored for strong language and scenes some viewers may find upsetting]. I am only partly joking here; if you find yourself in this sort of situation normally it is because something has gone terribly wrong upstream. We can work around it, though.
Step two: use who with the filename to get a list of variables in that file
names = who('-file', 'all');
Step three: load the variables (or a subset of them) into a struct
data = load('all.mat');
Step four: use dynamic structure naming to extract data:
for n = 1:length(names);
plot(data.(names{n})); % or whatever you want to do with this data
end
I would probably just use the loop to dump the data in a cell array so as to make further processing simpler and avoid further use of dynamic field names or worse, eval.
You can use who, which lists all variables alphabetically in the active workspace.

Workspace struct array input to Simulink M file S function

I would like my Simulink Level 2 S function to sequentially run a series of test cases. Each test case populates a struct containing multiple numerical arrays.
I am currently trying to achieve the above in two steps:
Step 1: generate test cases using a M file, save to Workspace as an array of structs
Step 2: read the array of structs from the Workspace into my model, using a Level 2 M
file S function to process the test cases.
Step 2 is problematic for me, in that I cannot figure out a way to get the S-function block to accept the array-of-structs variable from the Workspace as input. I want to try avoiding the simin method (another Stackoverflow discussion, here), because it seems to require representing the entire structure as a single data column, and I would like to keep the struct intact. Also tried using a Constant block with the struct array as the variable name, but that returns an 'Invalid setting for blockname parameter Value' for the block.
Would appreciate any suggestions for getting this set up correctly. Also open to a different method of building the model, if absolutely necessary. Thanks!
EDIT: Realized that I can import the data within the S function M file itself, using load. This works for the purposes of my project. However, am still interested in knowing whether a conventional solution exists for this.
If you just want to access the workspace, I would consider using evalin(caller,'expression') inside you M-file S-function:
mystruct = evalin('base','MyStructFromWorkspace');
/* (process mystruct) */
It should also do the trick.