The Math Forum

Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Math Forum » Discussions » Software » comp.soft-sys.matlab

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

Topic: Question on a function with changing sign
Replies: 2   Last Post: Jan 20, 2014 9:25 AM

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View   Messages: [ Previous | Next ]

Posts: 9,850
Registered: 6/7/07
Re: Question on a function with changing sign
Posted: Jan 20, 2014 9:25 AM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply

On 1/19/2014 10:45 PM, Allen wrote:
> I am a newbie on MATLAB and start learning it now. I was told that it
> takes less time on using vector operation than loops. Here is my function,
> zi = (-1)^i * x^2
> I can do the following:
> z = x.^2 but I am wondering how to do this to get the (-1)^i without
> using a loop.
> (for using a loop, that would be easy but I want to try something new.)

You _can_, of course, use the exponential operator there, too, but it's
also not very efficient/optimal as is I presume the reason for the post.

Several alternative ways -- the loop _may_ not be so bad a solution,
however, if you are only building a sum, say, and don't need the
intermediate terms. But, that aside, easiest is to start with ':' --

ix=ones(N,1); % for some N
ix(1:2:end)=-1; % negate alternates

or, slightly different is repmat --

ix=repmat([-1 1],1,N/2); % repeat the alternate for N total length

Many variations upon a theme are possible...


Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© The Math Forum at NCTM 1994-2018. All Rights Reserved.