How do I create a for loop for the this example?

Dear all, I have a code as follow:
for i = 1:5
syms (['X_' , num2str(i)])
end
J = (X_2 - X_1)^2 + (X_3 - X_2)^2 + (X_4 - X_3)^2 + (X_5 - X_4)^2 ;
B_1 = diff(J,X_1)/2 ; B_2 = diff(J,X_2)/2 ; B_3 = diff(J,X_3)/2 ; ...
B_4 = diff(J,X_4)/2 ; B_5 = diff(J,X_5)/2 ;
unknown = [X_1 X_3 X_4 X_5];
Now I would like to do the below operation for all from B_1 until B_5 in a loop
B_1sorted = collect(B_1,unknown); %Sort symbols from Psi_1 to Psi_100
[c,t] = coeffs(B_1,unknown);
index = 0;
newc = zeros(1,length(unknown));
for k = 1:length(unknown)
if any(t==unknown(k))
index = index + 1;
newc(k) = c(index);
end
end
any help would be greatly appreciated,

3 comentarios

Stephen23
Stephen23 el 18 de Dic. de 2017
Editada: Stephen23 el 18 de Dic. de 2017
You should read this:
If you only have five variables then using a loop and eval is a total waste of time and only serves to make your code slow, complex, obfuscated, and pointlessly hard to read. Why bother?
Rather than writing this awkward code, simply use an array. Indexing is neat, fast, easy to debug, easy to understand, and highly efficient. Or perhaps define a simple function and call that. But using eval on this problem is like cracking a walnut with steamroller.
ehsan
ehsan el 18 de Dic. de 2017
Thank you Stephen,
Thanks for your useful link and prompt response.
Actually, you are right, but in my case, I have a lot of variables (it can be 200 or much more).
The way Kaushik did according to my codes, it makes code slow but it works.
Regards,
I agree with Stephen. I suggested eval only because your set up used symbolic variables and I assumed you were simply looking for a quick hack. This solution is not sustainable if you have many more variables.

Iniciar sesión para comentar.

 Respuesta aceptada

You can use eval. Something like this should work, although you need to take care of saving your variables at the end of each iteration.
for i=1:5
eval(['B_' num2str(i) 'sorted = collect(B_1,unknown)']);
[c,t] = coeffs(eval(['B_' num2str(i)]),unknown);
index = 0;
newc = zeros(1,length(unknown));
for k = 1:length(unknown)
if any(t==unknown(k))
index = index + 1;
newc(k) = c(index);
end
end
%%save your variables from the i^th iteration
end

1 comentario

ehsan
ehsan el 18 de Dic. de 2017
Thank you Kaushik, for your prompt reply. Your solution works nicely.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Variables en Centro de ayuda y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by