How can I do to avoid using eval?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
sc
el 17 de Sept. de 2018
Respondida: Guillaume
el 17 de Sept. de 2018
Hi! I'm modifying a code created with Matlab but I have a problem: I'd like to avoid using the eval function and at the same time create arrays that contain a variable number of elements.
For example, in this part of code
num_int = 3;
for k = 1 : num_int
eval(['m = length(I',num2str(k),')'])
for i = 1 : m
if count_vector(k) == 0
eval(['ydata_low_',num2str(k),'(i,:) = [I',num2str(k),'_0(i) I',num2str(k),'_1(i) I',num2str(k),'_2(i) I',num2str(k),'_3(i) I',num2str(k),'_4(i)]']);
eval(['ydata_high_',num2str(k),'(i,:) = [I',num2str(k),'_5(i) I',num2str(k),'_6(i) I',num2str(k),'_7(i) I',num2str(k),'_8(i)]']);
end
end
I should create ydata_low and ydata_high, in function of k (that is num_int and is worth is 3).
In short, six arrays should be created: ydata_low_1, ydata_low_2, ydata_low_3, ydata_high_1, ydata_high_2 and ydata_high_3. The program already creates the variables to be introduced into the matrices (see attachment). I'd also like that variables from I_0 to I_4 are inserted in data_low and the variables from I_5 to I_8 are inserted in data_high.
Thank you!!
0 comentarios
Respuesta aceptada
Guillaume
el 17 de Sept. de 2018
The code to fix is not the one you show unfortunately, It's the code before that which creates all these numbered I variables.
Do not create numbered variables. Matlab already has a way of storing together things with an index: matrices and cell arrays. Instead of all these Ix_y you should have a single I variable (and a better, more meaningful name wouldn't hurt) that is a cell array with I{1} a 3121x10 matrix, |I{2} a 3554x10 matrix, and I{3} and 3510x10 matrix (each made by horizontally concatenating [Ix, Ix_0, ..., Ix_9]. With that your correct code is trivial:
num_int = numel(I); %no more hardcoded size
for k = 1:num_int
if count_vector(k) == 0
y_data_low{k} = I{k}(:, 2:5);
y_data_high{k} = I{k}(:, 6:10);
end
end
To be honest, there isn't even a need for y_data_low and y_data_high since it's simply I{k}(:, 2:5) and I{k}(:, 6:10) respectively.
0 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Logical 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!