Borrar filtros
Borrar filtros

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

1 visualización (últimos 30 días)
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

Respuesta aceptada

Mohammad Abouali
Mohammad Abouali el 30 de Nov. de 2014
Editada: Mohammad Abouali el 30 de Nov. de 2014
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 comentario
Goldie
Goldie el 30 de Nov. de 2014
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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Function Creation en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by