Why doesn't my script work. I try to create a vector in dependecy of variable without a loop. I'm not sure how i have to define the vector before the if cases

조회 수: 3 (최근 30일)
if true
% code
z=0:1:4000;
g_1=0;
g_2=0;
v(z)=NaN(length(z));
for b=1:length(z)
if z<2000
v(z)=1500+z*g_1;
elseif z>=2000
v(z)=2000+z*g_2;
end
end
end

채택된 답변

Birdman
Birdman 2017년 11월 16일
z=0:1:4000;
g_1=0;
g_2=0;
v=NaN(1,length(z));
for b=1:length(z)
if z(b)<2000
v(b)=1500+z(b)*g_1;
elseif z(b)>=2000
v(b)=2000+z(b)*g_2;
end
end
  댓글 수: 3
Stephen23
Stephen23 2017년 11월 16일
@Sebastian: you would be better off learning how to use MATLAB effectively. See KL's answer for a much neater solution.
Jan
Jan 2017년 11월 25일
I mention this, because it occurs in many code posted in the forum:
After
if z(b)<2000
it is useless to check for:
elseif z(b)>=2000
A simple else is sufficient already: It runs faster and the simpler code reduces the chance for typos.
This is not really important for Sebastian's question, but recommending to omit redundant code will make it easier to debug and maintain the code in general.

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

추가 답변 (1개)

KL
KL 2017년 11월 16일
No need for a loop, use logical indexing. Here's a better way to write that,
indx = z<2000;
v(indx) = 1500+z(indx)*g_1;
v(~indx)=2000+z(~indx)*g_2;
  댓글 수: 4
Jan
Jan 2017년 11월 25일
+1. Or shorter:
idx = (z >= 2000);
v = 1500 + 500 * idx + z .* (g_1 .* (~idx) + g_2 .* idx);
With reordering the terms this is running 3 times faster:
v = (1500 + z .* g_1) .* ~idx + (2000 + z.* g_2) .* idx;

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

카테고리

Help CenterFile Exchange에서 Function Creation에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by