# Problem renaming variable in loop

1 visualizzazione (ultimi 30 giorni)
amir il 5 Lug 2023
Problem renaming variable in loop
In the last loop, suppose I want to get the Hilbert transform from the 150 variables Is1...Is150 in the commented part of the loop.
What should I do????
clc
clear
close all
Rf1=[0.001 10 50 100 200];
L_line1=[4 50 100 140 150 196];
tetta1=[10 -15 20 30 40];
for i=1:150
if i<=30
f1(i)=Rf1(1);
elseif i<=60
f1(i)=Rf1(2);
elseif i<=90
f1(i)=Rf1(3);
elseif i<=120
f1(i)=Rf1(4);
else
f1(i)=Rf1(4);
end
end
for i=1:30
if i<=5
f2(i)=L_line1(1);
elseif i<=10
f2(i)=L_line1(2);
elseif i<=15
f2(i)=L_line1(3);
elseif i<=20
f2(i)=L_line1(4);
elseif i<=25
f2(i)=L_line1(5);
else
f2(i)=L_line1(6);
end
end
for i=1:150
f1_1=num2str(f1(i));
prt1=strcat(f1_1,'_');
for i2=1:30
f2_2=num2str(f2(i2));
prt2=strcat(f2_2,'_');
for i3=1:5
f3_3=num2str(tetta1(i3));
prt3=strcat(f3_3,'\');
If=cell2mat(Y);
If_1=If(1999:2401);
eval(['If', num2str(i) , ' =If_1;']);
Is=cell2mat(Y);
Is_1=Is(1999:2401);
eval(['Is', num2str(i) , ' =Is_1;']);
end
end
end
t1=cell2mat(Y);
time=t1(2001:2400);
%% D
for i=1:150
eval(['Is1', num2str(i) , '= hilbert'(eval(['Is', num2str(i)]))]);
end
##### 3 CommentiMostra 1 commento meno recenteNascondi 1 commento meno recente
KALYAN ACHARJYA il 5 Lug 2023
Modificato: KALYAN ACHARJYA il 5 Lug 2023
Additionally, you may utilize the piecewise function, which will help reduce the number of if-else statements.
John D'Errico il 5 Lug 2023
Modificato: John D'Errico il 5 Lug 2023
Please don't use an answer to do nothing more than say thanks to someone unspecified. And then worse, ACCEPT IT AS THE CORRECT ANSWER.

Accedi per commentare.

### Risposte (1)

Nathan Hardenberg il 5 Lug 2023
Modificato: Nathan Hardenberg il 6 Lug 2023
Having 150 variables all having to do with one thing is not good coding. You should use a matrix/array/cells instead. Also using eval() to assign or call a variable is not very good as well. You should avoid those practices.
Is1 = -1; Is2 = 4; Is3 = 3; Is4 = 2; % "your" variables
N = 4; % N=150 in your example
xr = zeros(1,N); % predefine matrix
for i=1:N
xr(i) = eval(['Is', num2str(i)]); % write all your variables into the matrix
end
X = hilbert(xr) % do the hilbert transform
X =
-1.0000 - 1.0000i 4.0000 - 2.0000i 3.0000 + 1.0000i 2.0000 + 2.0000i
Edit: To be more clear, since @Stephen23 posted a very useful link in the comments. This style of coding using eval() should not be done! My answer is just a working solution, with the given situation, without changing the intire code. But changing the intire code would be recommended with reasons written in the link.
##### 1 CommentoMostra -1 commenti meno recentiNascondi -1 commenti meno recenti
Stephen23 il 5 Lug 2023

Accedi per commentare.

### Categorie

Scopri di più su Programming in Help Center e File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by