필터 지우기
필터 지우기

How can I put variable equal to zero in loop

조회 수: 3 (최근 30일)
Adham Ahmed
Adham Ahmed 2023년 2월 8일
댓글: Adham Ahmed 2023년 2월 8일
in this code
w= input('k=');
for k=1:w
m=sym('U1',[1 k])
end
I need to put U1k in every iteration =0
U11=0
U12=0
U13=0 .......
  댓글 수: 1
Adham Ahmed
Adham Ahmed 2023년 2월 8일
thank you
I need for k=1
U11=0
for k=2
U12=0
for k=3
U13=0
an so on.........
for k=9
U19=0
using loop

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

답변 (3개)

Dinesh
Dinesh 2023년 2월 8일
Hi Adham Ahmed,
For any input 'w', to create that many number of variables during run time, 'sprintf' function can be used.
Then the 'eval' function can be used to initialize them to zero as you wanted to do.
The following code takes an input 'w' and then creates that many number of variables namely U11, U12, ...., U1w at run time and initializes all of them to zero.
w = input('k='); % takes an input 'w'
for k = 1:w
var_name = sprintf('U%d%d', 1, k); % creates the dynamic variable name
eval([var_name '= 0;']); % initialization to zero
end
In the above code, for an example, if the input 'w' is 3, then you can print 'U13' using
disp(U13);
to confirm the variable creation and value assignment.
  댓글 수: 2
Steven Lord
Steven Lord 2023년 2월 8일
Can you dynamically create variables with numbered names like U11, U12, U13, etc.? Yes.
Should you do this? The general consensus is no. That Answers post explains why this is generally discouraged and offers several alternative approaches.
Adham Ahmed
Adham Ahmed 2023년 2월 8일
thank you
I need for k=1
U11=0
for k=2
U12=0
for k=3
U13=0
an so on.........
for k=9
U19=0
using loop

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


VBBV
VBBV 2023년 2월 8일
% using loop
w= 10; %input('k=');
for k=1:w
m=sym('U1',[1 k]) == 0;
end
m
m = 
you can also do so without using loop
% without loop
m=sym('U1',[1 w]) == 0
m = 
  댓글 수: 2
Adham Ahmed
Adham Ahmed 2023년 2월 8일
thank you
but only the last one to be zero
Adham Ahmed
Adham Ahmed 2023년 2월 8일
thank you
I need for k=1
U11=0
for k=2
U12=0
for k=3
U13=0
an so on.........
for k=9
U19=0
using loop

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


Shubham
Shubham 2023년 2월 8일
Here's a code that sets the symbol 'U1k' to zero in each iteration:
w = input('k=');
for k = 1:w
eval(sprintf('U1%d=0', k))
end
  댓글 수: 1
Adham Ahmed
Adham Ahmed 2023년 2월 8일
thank you
I need for k=1
U11=0
for k=2
U12=0
for k=3
U13=0
an so on.........
for k=9
U19=0
using loop

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

카테고리

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