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

23 次查看(过去 30 天)
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

采纳的回答

Arthur Roué
Arthur Roué 2020-8-5
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Variables 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by