dpb
Posts:
9,332
Registered:
6/7/07


Re: Question on a function with changing sign
Posted:
Jan 20, 2014 9:25 AM


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...


