change two variable in the name in a loop using eval or any other command
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Abdulmajid Mrebit
am 18 Mär. 2019
Beantwortet: Abdulmajid Mrebit
am 18 Mär. 2019
Hi I´m having a problem with this code:
HOw can I change both the M and N in the varibles of P_M_out_N names in a loop. Ithe following colud change N with loop
but I do not know how to change M values in the loop.
clc; clear all; close all
%P_M_out_N = u^j
u=3;
j=1:5;
M= [1 8 6 2 4];
N =[2 3 7 8 12]
for j = 1:length(M)
eval(sprintf('M_out_of_%d=u^j', N(j)))
end
%%
P_1_out_2 = u
P_8_out_3 = u^2
P_6_out_7= u^3
P_2_out_8 = u^4
P_4_out_12 = u^5
1 Kommentar
Stephen23
am 18 Mär. 2019
Bearbeitet: Stephen23
am 18 Mär. 2019
Dynamically defining or accessing variable names is one way that beginners force themselves into writing slow, complex, obfuscated, buggy, hard-to-debug code. Read this to know why:
Not only that, but the including meta-data into variable names or fieldnames makes code slow, complex, and fragile. Read this to know why:
In your case you can easily write much simpler, neater, more efficient code, just like experienced MATLAB users would:
>> u = 3;
>> M = [1,8,6,2,4];
>> N = [2,3,7,8,12];
>> V = u.^(1:numel(N))
V =
3 9 27 81 243
and just then use basic MATLAB indexing to access the corresponding vector elements. Indexing is simple, neat, easy to debug, and very efficient (unlike what you are trying to do).
Akzeptierte Antwort
madhan ravi
am 18 Mär. 2019
Bearbeitet: madhan ravi
am 18 Mär. 2019
I suggest you to use struct with dynamic field names ( https://blogs.mathworks.com/loren/2005/12/13/use-dynamic-field-references/ ) , using eval() is not a good idea ( https://in.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval )
for k=1:numel(M)
s.(sprintf('P_%d_out_%d',M(k),N(k)))=u^k;
end
0 Kommentare
Weitere Antworten (1)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!