Read in matrix for multiple steps while changing string

조회 수: 1 (최근 30일)
Alexandra Vest
Alexandra Vest 2023년 5월 24일
댓글: Steven Lord 2023년 5월 24일
Hi, I want to read in multiple temperature files at different time steps. For instance I have array:
time = [0, 10, 20];
And I need to read in:
temp0 = "temperature_0.txt"
temp1 = "temperature_10.txt"
temp2 = "temperature_20.txt"
So I can compile them all into:
temp = [temp0;temp1;temp2]
How can I handle changing the string names "temp0" and "temperature_0.txt" based on the value in time? I know I will have a for loop such as follows, but I am unsure of how to make the variable input into the name as a string
for k = 1:length(time)
...
end

채택된 답변

Steven Lord
Steven Lord 2023년 5월 24일
time = [0, 10, 20];
files = "temperature_" + time + ".txt"
files = 1×3 string array
"temperature_0.txt" "temperature_10.txt" "temperature_20.txt"
Now you could iterate over the elements of the files string array.
  댓글 수: 3
Alexandra Vest
Alexandra Vest 2023년 5월 24일
A follow-up question, if I have a bunch of file, let's say "log_0.txt", "log_10.txt" "log_20.txt" and I wanted to read in the numbers on the latter end of the file name to create the array time=[0,10,20] is there a way to do that? I don't need to read in those files, just take the number following log_. Thank you!
Steven Lord
Steven Lord 2023년 5월 24일
If the only digits in the names are in the numbers you want to extract, use digitsPattern to extract that data from the string array.
time = [0, 10, 20];
files = "temperature_" + time + ".txt"
files = 1×3 string array
"temperature_0.txt" "temperature_10.txt" "temperature_20.txt"
numbersAsText = extract(files, digitsPattern)
numbersAsText = 1×3 string array
"0" "10" "20"
numbers = double(numbersAsText)
numbers = 1×3
0 10 20
isequal(time, numbers)
ans = logical
1

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Cell Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by