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!