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