Carmaker ASCII to Matlab code
4 ビュー (過去 30 日間)
古いコメントを表示
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
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
回答 (1 件)
Arnav
2024 年 9 月 4 日
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:
- Documentation for string functions: https://www.mathworks.com/help/matlab/characters-and-strings.html?s_tid=srchbrcm
- Documentation for assignin: https://www.mathworks.com/help/matlab/ref/assignin.html?searchHighlight=assignin&s_tid=srchtitle_support_results_1_assignin#responsive_offcanvas[BS2]
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Event Functions についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!