필터 지우기
필터 지우기

How to assign a value to a variable in for loop?

조회 수: 22 (최근 30일)
azarang asadi
azarang asadi 2022년 10월 14일
댓글: Jan 2022년 10월 15일
Hello all,
I'm getting some input from the user to create the name of a variable as follow:
LocationIMU = string(input('thigh/shank/foot?','s')); %'thigh'
Side = string(input('paretic/non?','s')); %'paretic'
Component = string(input('X/Y/Z/Ox/Oy/Oz?','s')); %'X'
File = string(input('acceleration or angular velocity?','s')); %'acceleration
assignin('base',strcat(LocationIMU,'_' ,File ,'_' ,Component ,'_' ,Side, '_Good'),zeros(101,1));
up to here I get what I want, a variable named thigh_acceleration_X_paretic_Good ( considering the comments as input).
Now I need to creat a for loop and in this for loop I'll be adding new columns to this variable but as this variable can change accordingto input, I don't want to hard code it and need to find a way to add the columns to it. Here's what I am trying to do but as said I don't want it to be hard coded:
for i =1:endLoop
signal = 1:100;
thigh_acceleration_X_paretic_Good (:,end+1) = signal;
end
here I hard coded the variable name, how could I do it without writing the variable name and instead having it from inputs?
I hope I could explain what I mean.
  댓글 수: 1
Stephen23
Stephen23 2022년 10월 14일
"I hope I could explain what I mean."
We understand what you mean, and we also know that the answer is always the same: do NOT do this.
Meta-data (e.g. location, component, side names) is data, and data belongs in variables (not in variable names). Once you store meta-data in variables, then your code will be neat, simple, and efficient (unlike with what you are trying to do).

댓글을 달려면 로그인하십시오.

채택된 답변

Jan
Jan 2022년 10월 14일
This is the most frequently asked question from beginners. Professional programmers give the simple and not expected answer: Don't do this! You drill a hole in your own knee.
Do not store important information in the name of variables, but in their values.
  댓글 수: 3
Walter Roberson
Walter Roberson 2022년 10월 14일
Who imposed the external requirement that you create dynamic variable names?
Jan
Jan 2022년 10월 15일
@azarang asadi: As said already, this is the question asked most frequently by beginners. Others and me have dicussed this exhaustively hundreds of times. The results was always the same: You are the programmer and you can write cleaner and better and most of all working code.
Take the chance to learn from the mistakes of others.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by