Reputation: 1654
I have written a short Octave script which draws the function sum(sin(2k-1)/(2k-1))
for k = 1..n
terms. (I am attempting to model how successive terms make the output converge to a square wave.
% Program to model square-wave using sum of sines
terms=3
theta=linspace(0, 6*pi, 1000);
k=[1:terms]';
n=2*k-1;
q=sin(n*theta)./n;
y=sum(q);
plot(theta, y);
It works OK (i.e. the sum()
function returns a vector containing the sum of each column) for terms > 1. But when terms == 1 (i.e. it should just draw a sine wave) the sum()
function computes the sum of the row and just returns a scalar.
How do I get the sum()
function to total each column even if there is only one row or how do I reshape or slice or whatever the row vector such that rather than being a 1-dimensional vector of dimension n it effectively becomes a 2-dimensional matrix of dimension 1xn?
Upvotes: 0
Views: 7612
Reputation: 13081
sum()
, like many other functions in Octave, will act on the first non-singleton dimension by default. So all you need to do is to be specific about the dimension. From sum()
help text:
If DIM is omitted, it defaults to the first non-singleton dimension.
So, all you need to do is be specific about the dimension, i.e., use sum (q, 1)
:
terms = 1
theta = linspace (0, 6*pi, 1000);
k = [1:terms]';
n = 2*k-1;
q = sin (n*theta) ./ n;
y = sum (q, 1);
plot (theta, y);
Upvotes: 8
Reputation: 64
q=sin(n*theta)./n;
if (terms == 1)
y = q;
else
y=sum(q);
end
plot(theta, y);
See if that works.
Upvotes: -1