1

I'm trying to write an if-else statement that sets a value of an array to 0.1 at n=0 because the equation that computes that array has undetermined value at that input. The equation is:

enter image description here

So at 0 the value is infinity.

This is the code I wrote but it doesn't seem to work:

n = -(N-1)/2:(N-1)/2;
hlp = (1./n*pi).*(sin(0.1*pi.*n));

if n == 0
    hlp = 0.1;
else
    hlp = (1./n*pi).*(sin(0.1*pi.*n));
end
1
  • For refference, the issue you have in your code is that its not a loop, so n is never n==0, as n = -(N-1)/2:(N-1)/2;. Your code would work with a couple of changes: make a for loop for ii=n, and then access each variable per value ( n(ii) and hlp(ii)). That is what is flawed in your logic. The one liner solution is better, but sometimes you can't avoid loops. Commented Oct 31, 2022 at 14:34

1 Answer 1

3

I think that you are close. See if this works.

n = ( -(N-1)/2  ):(  (N-1)/2  );    %add some parentheses here
hlp = (1./n*pi).*(sin(0.1*pi.*n));  %this line is unchanged

When working on a subset of a vector, if/else isn't really the right construct. Try this instead.

%create a mask of the elements to replace
maskN0 = (n==0)
%then replace them
hlp(maskN0) = 0.1;

OR, after you've been doing this a while, it may be more natural to write (Thanks Ander Biguri)

hlp(n==0) = 0.1;
%When I read this, I hear: "hlp, where n=0, set to 0.1"
Sign up to request clarification or add additional context in comments.

3 Comments

Are you sure help() will replace it? Because help in MATLAB is used to explain what the function does.
There was a critical.typo. help instead of hlp. Updated
You can even shorten this to hlp(n==0)=0.1; which makes it more readable, imho.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.