필터 지우기
필터 지우기

Convert nearly created string in a structure format to a variable name in a for loop

조회 수: 1 (최근 30일)
Hey there,
I been trying to convert a nearly created string to a variable in a for loop and I cam struggling to find the correct function to convert it.
I have included a simple example problem below which details the problem. Thanks in advance for your help
if true
close all
clear all
clc
% Two cars referened as Car01 and Car02 are studied
% Two variables are recored 1st column= time (s), 2nd column = distanc (m)
A.Car01.speed = [1 2 3 4 5; 10 20 30 40 50 ]';
A.Car02.speed = [1 2.1 3.3 4.5 5; 11 19 33 42 51]';
% Want to interpolate the distance of both cars travelled in a loop
for k=1:2
% Create a mat filename, and load it into a structure called matData.
matFileName = sprintf('A.Car%02d.speed', k);
temp_col = (eval(matFileName));
temp_time = temp_col(:,1);
temp_speed = temp_col(:,2);
Final_lenght = 10;
Interpolation_f = temp_time(end)/Final_lenght;
Interp_time = 0:Interpolation_f:temp_time(end);
temp_speed = interp1(temp_time,temp_speed,Interp_time);
temp_name = sprintf('A.Car%02d.speed_interp', k);
% I want to save the newly created variable A.Car01.speed_interp =
% temp_speed and A.Car02.speed_interp as the other calculated speed in
% the for loop
% cellstr(temp_name) = temp_speed does not work
end
end

채택된 답변

Mohammad Abouali
Mohammad Abouali 2014년 11월 30일
편집: Mohammad Abouali 2014년 11월 30일
I code it something like this: (note the use of ( ) while referencing structure fields with string, such as A.(carNumber).speed where carNumber is 'Car01'
clear all
clc
A.Car01.speed = [1 2 3 4 5; 10 20 30 40 50 ]';
A.Car02.speed = [1 2.1 3.3 4.5 5; 11 19 33 42 51]';
for k=1:2
carNumber = sprintf('Car%02d', k);
temp_time = A.(carNumber).speed(:,1);
temp_speed = A.(carNumber).speed(:,2);
Final_lenght = 10;
Interpolation_f = temp_time(end)/Final_lenght;
Interp_time = 0:Interpolation_f:temp_time(end);
A.(carNumber).speed_interp = interp1(temp_time,temp_speed,Interp_time);
end
By the way, this way of interpolating will have some NaN in the beginning. Your time data vector starts from 1 but when interpolating you start Interp_time from 0. I did not changed that assuming that is what you want.
  댓글 수: 1
Goldie
Goldie 2014년 11월 30일
Thats exactly what I wanted, thanks very much for the speedy reply aswell.
I was aware the method of interpolating resulted in NaN values but I just included this as a simple example of what I was trying to do.
Thanks again for your answer.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Function Creation에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by