Special variable name in MATLAB [duplicate] - matlab

If for instance I have a variable xa=2, and then I construct a string by joining 'x' and 'a', how can I make this new string have the value 2?
xa=2;
var=strcat('x','a');
The result of this is var=xa, but what I want is var=2.
Thank you

Use eval():
var = eval(strcat('x','a'));
It will "evaluate" the string 'xa' and translate it to the value of the variable xa.
Source : MATLAB documentation

Related

Scala- Databricks- Linear Regression

Can someone please explain me the meaning of below line of code (in scala-databricks)
val categoricalIndexers = categoricalVariables
.map(i => new StringIndexer().setHandleInvalid("skip").setInputCol(i)
.setOutputCol(i+"Index"))
The aim of the StringIndexer is to map a string column of labels to an ML column of label indices (see the documentation of Apache Spark for more details and codes(.
You can use setHandleInvalid to choose how the unseen labels are handled using the StringIndexer. If you choose the "skip" setting the rows containing the unseen labels will be skipped (removed from the output).
And the aim of the end of the code .setInputCol(i) and .setOutputCol(i+"Index") is to index the string variables and to return the indexed variables; the names of the indexed variables are the names of the original string variables + "Index". For example, let's use the string variable "City". Once the string variable is indexed, the name of the indexed variable will be CityIndex.
You can use the following lines to index all the string variables of your data set :
var categoricalCols = DataSet.dtypes.filter(_._2 == "StringType").map(_._1)
var indexOutputCols = categoricalCols.map(_ + "_Index")
// Handle string variables
var stringIndexer = new StringIndexer()
.setInputCols(categoricalCols)
.setOutputCols(indexOutputCols)
.setHandleInvalid("skip")
The indexed variables have the original name + "_indexed".

Create a fixed size 3 dimensional array of type string

I am trying to create a fixed size 3 dimensional array in Swift with datatype of string like this:
var 3dArray:[[[String]]] = [[[50]],[[50]],[[50]]]
But it is giving error:
Cannot convert value of type 'Int' to expected element type string
From your question title you are trying to create 3d array with datatype [[[String]]] and in your question detail you are assigning it an Int value which is not possible in swift. That's why you are getting an error. Because your 3dArray object is expecting a String values
Either you can assign String values this way:
var yourArr: [[[String]]] = [[["50"]],[["50"]],[["50"]]]
Or if you want to make Int array you can do it this way:
var yourArr: [[[Int]]] = [[[50]],[[50]],[[50]]]
Note:
As #Martin R suggested variable names cannot start with a digit.
There is no typical way of creating multidimensional arrays in Swift.
But, you can create an array which will contain only String arrays and then append 3 different String arrays. Please find the code below:
var array = [[String]]()
array.append([String]())
array.append([String]())
array.append([String]())
At the end your array will be looking this way:
[[], [], []]
Or you can just create same array this way:
var array:[[String]] = [["50"],["50"],["50"]]
But keep in mind, "50" are strings which are content of those arrays and not their size.
If you want to have a fixed-size array, then you have to use some third party solutions like this one.

define variable by concatenating strings

I want to iteratively define a variable whose name is the concatenation of two strings.
In particular, the following code is meant to create a variable Uvel_spring that contains the values Uvel stored in the file spring_surface.mat :
seasons{1}='spring';
seasons{2}='summer';
seasons{3}='autumn';
seasons{4}='winter';
for ii=1:4
['Uvel_',char(seasons(ii))] = load([char(seasons(ii)),'_surface.mat'],...
'Uvel');
end
However, I get the following error:
An array for multiple LHS assignment cannot contain LEX_TS_STRING.
I solved it by using evalc:
for ii=1:4
evalc( sprintf(['Uvel_',char(seasons(ii)),'=','load(''',char(seasons(ii)),'_surface.mat'',',...
'''Uvel''',')']) );
end
However, it is horrible and I would like to improve the code.
Does someone have an alternative solution?
Use struct instead.
for ii=1:4
Uvel.(seasons{ii}) = load([seasons{ii},'_surface.mat'], 'Uvel');
end
You'll end up having those four seasons as the fields of Uvel. So you'll be accessing Uvel_spring as Uvel.spring and similarly for others.

String to variable name MATLAB

If for instance I have a variable xa=2, and then I construct a string by joining 'x' and 'a', how can I make this new string have the value 2?
xa=2;
var=strcat('x','a');
The result of this is var=xa, but what I want is var=2.
Thank you
Use eval():
var = eval(strcat('x','a'));
It will "evaluate" the string 'xa' and translate it to the value of the variable xa.
Source : MATLAB documentation

MATLAB assign variable name

I have a variable called 'int' with alot of data in it. I would like to find a way to programically rename this variable with a user input. So I can query the user indentifcation information about the data, say the response is 'AA1', I want either rename the variable 'int' to 'AA1' or make 'AA1' a variable that is identical to int.
A problem using the input command arises because it allows the user to assign a value to an already created varialbe, instead of actually creating a variable name. Would using the eval function, or a variation of it, help me achieve this? Or is there an easier way?
Thanks!
Just for the record, int is a rather poor variable name choice.
That aside, you can do what you want as follows
say foo is the variable that holds a string that the user input. You can do the following:
% eliminate leading/trailing whitespace
foo = strtrim(foo);
a = regexp('[a-zA-Z][a-zA-Z0-9_]*',foo));
if numel(a) == 0
fprintf('Sorry, %s is not a valid variable name in matlab\n', foo);
elseif a ~= 1
fprintf('Sorry, %s is not a valid variable name in matlab\n', foo);
elseif 2 == exist(foo,'var')
fprintf('Sorry, %s already in use as a variable name.');
else
eval([foo,' = int']);
end
Assuming int (and now foo) is a structure with field named bar, you can read bar as follows:
barVal = eval([foo,'.bar']);
This is all somewhat clunky.
An alternative approach, that is far less clunky is to use an associative array, and let the user store various values of int in the array. The Matlab approach for associative arrays is Maps. That would be my preferred approach to this problem. Here is an example using the same variables as above.
nameValueMap = containers.Map;
nameValueMap(foo) = int;
The above creates the association between the name stored in foo with the data in the variable int.
To get at the data, you just do the following:
intValue = nameValueMap(foo);