Carmaker ASCII to Matlab code

4 次查看(过去 30 天)
Arsiv
Arsiv 2024-4-18
回答: Arnav 2024-9-4
hey guys, i have a testrun file from matlab which is an ASCII text and I want to hardcode this text to matlab for my simulation. It also contains many parameters required for the simulation. How to do this?
  2 个评论
Harald
Harald 2024-4-18
Hi,
in the title, you mention Carmaker, so I suppose you have a testrun file from Carmaker rather than MATLAB. Since most people here, including myself, will not know what this looks like, it will be good if you can attach an example. This may help understand the actual question.
Best wishes,
Harald
Arsiv
Arsiv 2024-4-23
编辑:Arsiv 2024-4-23
Hello, here is the snippet!

请先登录,再进行评论。

回答(1 个)

Arnav
Arnav 2024-9-4
Hi @Arsiv,
To read the values of the parameters, you need to parse the file and extract the key-value pairs separated by =. These key-value pairs can be stored in a map. After opening the file with fopen, you can parse the file as follows:
configMap = containers.Map();
while ~feof(fid) % Parse the File
line = strtrim(fgetl(fid)); % Read a line and trim whitespace
tokens = strsplit(line, '='); % Split into key and value
key = strtrim(tokens{1});
value = strtrim(tokens{2});
configMap(key) = value; % Store the key-value pair in the map
end
Here I have used strtrim to trim whitespace from the lines that are read. Then strsplit function is used to split the line using delimeter =.
You can use the parameters you want to access using the configMap variable.
Optionally, you can create dynamic variables to store the key-value pairs as actual variables using assignin since your question was about hard coding the variables into MATLAB code. This can be done in 2 steps:
  • Preprocess the variable names by replacing the . character with _ using strrep since a name like Vehicle.0.mass is not a valid variable name.
validVarName = strrep(key, '.', '_');
  • Use assignin to create a variable in the base workspace.
assignin('base', validVarName, value);
But however, this should be done with caution, as dynamically creating variables can lead to code that is harder to maintain and debug.
You can learn more about the functions that I have used here:

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by