필터 지우기
필터 지우기

inserting index for variable

조회 수: 4 (최근 30일)
shirin mhd
shirin mhd 2022년 4월 1일
편집: Torsten 2022년 4월 1일
Hi everyone!
I want make index for my variable. I write a simple code:
x=8;
b=9;
for i=1:2
w(i)=x+b
u=x+w(i)
end
I expect something like this:
w(1)=17
u(1)=8
w(2)=17
u(2)=25
but code doesnt do this.
Since I've just started programming with MATLAB. Im not familiar with this syntax.
I appreciate any help.
  댓글 수: 1
Riccardo Scorretti
Riccardo Scorretti 2022년 4월 1일
편집: Riccardo Scorretti 2022년 4월 1일
Dear Shirin,
in your code, the variable u is not a vector. Try this:
x=8;
b=9;
for i=1:2
w(i)=x+b
u(i)=x+w(i)
end
w = 17
u = 25
w = 1×2
17 17
u = 25
However, notice that in this way your vector will be increasing; this is a bad practice from the point of view of computational efficiency.
Most importantly, there is strictly no reason for you to obtain the result you posted beause w(i) = x+b = 17 for any index i, hence u(i) = x+w(i) = 2x+b = 25 is constant as well (no matter if u is a vector or a scalar). Are you sure of your algorithm?

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

답변 (1개)

Torsten
Torsten 2022년 4월 1일
편집: Torsten 2022년 4월 1일
I don't know what you mean by "I want make index for my variable", but
x = 8;
b = 9;
w = zeros(2,1);
u = zeros(2,1);
for i = 1:2
u(i) = x + w(i);
w(i) = x + b;
end
at least reproduces your expected output.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by