How can I assign strings from array to variable name from another array with same size?

21 views (last 30 days)
There are two arrays with the same size. Bothe arrays are filled with strings. The target is to use the strings from the first array as variable names and the strings from the other array as values in form of string. This means to assign first string from the other array to the first string from the first array and the second string from the other array to the second string from first array.
Target as example:
calbelength = long
cablecrosssection = small
fuseboxname = FuseBox2
Matlab Code:
Matrix_parameter_string = ["calbelength","cablecrosssection","fuseboxname"]
Matrix_value_string = ["long","small","FuseBox2"]
[line,coloumn] = size(Matrix_parameter_string)
p = coloumn;
for t = 1:p
eval(fprintf('%s=%s',Matrix_parameter_string(1,t),Matrix_value_string(1,t))); % Assign value to parameter name
end
Matlab shows following error in command window:
calbelength=longError using eval
Must be a string scalar or character vector.
Error in Untitled (line 6)
eval(fprintf('%s=%s',Matrix_parameter_string(1,t),Matrix_value_string(1,t))); % Assign value to parameter name
By the way, if the values are double instead string. This would be the solution:
for t = 1:p
eval(sprintf('%s=%d;',Matrix_parameter_string(1,t),Matrix_value_double(1,t))); % Assign value to parameter name
end

Accepted Answer

Arthur Roué
Arthur Roué on 5 Aug 2020
You forgot the quote in your right side assignement
Matrix_parameter_string = ["calbelength","cablecrosssection","fuseboxname"];
Matrix_value_string = ["long","small","FuseBox2"];
[line,coloumn] = size(Matrix_parameter_string);
p = coloumn;
for t = 1:p
eval(sprintf('%s="%s"',Matrix_parameter_string(1,t),Matrix_value_string(1,t))); % Assign value to parameter name
end

More Answers (0)

Categories

Find more on Variables in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!