MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

New to MATLAB?

# Thread Subject: Negative indices in arrays

Subject: Negative indices in arrays

From: Chris G

### Jojo (view profile)

(Chris G)

Date: 13 Jun, 2009 23:57:01

Message: 1 of 9

Since matlab will not allow negative numbers or 0 of indices in arrays, how can I manipulate it to produce numbers for those negative indexes? I'm needing to calculate and plot on a stem plot an array going from -10 to 10 for a specified equation.

Subject: Negative indices in arrays

From: Kian

### Kian (view profile)

Date: 14 Jun, 2009 01:26:01

Message: 2 of 9

You need to be more specific. Give an example. This should be a easy problem to solve, but you need to give more clear.

Subject: Negative indices in arrays

From: Chris G

### Jojo (view profile)

(Chris G)

Date: 14 Jun, 2009 02:38:01

Message: 3 of 9

Alright, welll. For an assignment I'm trying to calculate and plot the values for n for when they are zero and negative for the magnitude and phase plot at the very end of the Prob2.m for Dn. The negative indices are giving me the most difficulties :

Prob2.m:

clc
clear all
close all
format compact
%format short eng

% Create a waveform from t=Tbegin to t=Tend
Tbegin = 0.0;
Tend = 5;

N = 2^15; Nm1=N-1; Np1=N+1; Nd2=N/2;

t=[0:Nm1]';
t=Tbegin + t*Tend/Nm1;
tsample = t(2)-t(1);

T0 = (Tend - Tbegin);
f0 = 1/T0;
w0 = 2*pi*f0;
fnyq = f0/2; wnyq=2*pi*fnyq;

NNN=100;

t1 = 2;
x = ((-2*t).*(rect_fcn((t-1.5)/3)))+(rect_fcn((t-4)/2)) ;
%x(t<=t1) = t(t<=t1);

% evaluate the analytic expression
n = 1:NNN;
Dn = ((((exp(-j*n*(6/5)*pi)).*(2-(2*j*n*(6/5)*pi)))-2)./((n.^2)*(4/5)*(pi^2)))+(((exp(-j*n*2*pi))-(exp(-j*n*(6/5)*pi)))./(-j*n*2*pi));

[a0,a,b]=fourier_series_coef(t,x,NNN);
% Uncomment the following line to see the coeficients values.
%a0, [a b];

Dn2a = 2*real(Dn);
Dn2b = -2*imag(Dn);
% had to make N=2^10 larger at the beginning to get better
% numerical integration results
NNNd = 10;
nnd=(1:NNNd);

disp(' a_n coef ')
[nnd' a(1:NNNd) Dn2a(1:NNNd)']
disp(' ')
disp(' b_n coef ')
[nnd' b(1:NNNd) Dn2b(1:NNNd)']
disp(' ')
disp(' Dn')
[nnd' Dn(1:NNNd).']
disp(' ')
disp(' |Dn|')
[nnd' abs(Dn(1:NNNd))']
disp(' ')
disp(' arg(Dn)')
[nnd' angle(Dn(1:NNNd))']

% use the FFT to compute ~Dn
XDn = fft(x)/N;
disp(' ')
disp(' ')
disp(' analytic Dn FFT Dn')
[Dn(1:NNNd).' XDn(2:NNNd+1)]

% Generate a waveform using the Fourier Series
xg = fourier_series_gen(t,T0,a0,a,b);
subplot(2,1,1),plot(t,x), grid on
ylabel('\it{x(t)}')
title('One Period of \it{x(t)}');

subplot(2,1,2), plot(t,xg), grid on
xlabel('t (sec)')
ylabel('\it{x^''(t)}');
titlestr = ['Fourier Series Approximation to {\itx(t)} (' ...
num2str(NNN) ' terms)'];
title(titlestr);

% Compare using partial sums of 5, 15 and 50 coeficients

Np=3;
tp=[0:(Np*N-1)]';
tp=Tbegin + tp*Np*Tend/(Np*N-1);

% 5
Ncoef = 5;
[a0,a,b]=fourier_series_coef(t,x,Ncoef);
amin = min([a0; a]); amax = max([a0; a]);
bmin = min(b); bmax = max(b);
xg5 = fourier_series_gen(tp,T0,a0,a,b);

% Plot Coefficients
f = [f0:f0:(Ncoef*f0)]';
figure

% a's
%subplot(2,1,1),stem([0; f],[a0; a],'r','LineWidth',3,'MarkerSize',5), grid
%xlabel('f (Hz)');
%ylabel('a_m');
%title('Cosine Coefficients');
%axis([-f0 (Ncoef+1)*f0 amin amax]);
% b's
%subplot(2,1,2), stem(f,b,'LineWidth',3,'MarkerSize',5), grid
%xlabel('f (Hz)');
%ylabel('b_m');
%title('Sine Coefficients');
%axis([-f0 (Ncoef+1)*f0 bmin bmax]);

% 15
Ncoef = 15;
[a0,a,b]=fourier_series_coef(t,x,Ncoef);
xg15 = fourier_series_gen(tp,T0,a0,a,b);

% 50
Ncoef = 50;
[a0,a,b]=fourier_series_coef(t,x,Ncoef);
xg50 = fourier_series_gen(tp,T0,a0,a,b);
figure, plot(tp,xg5,tp,xg15,tp,xg50), grid on
xlabel('t (sec)');
ylabel('\it{x''(t)}')
title('Partial Sum Approximations (5, 15, 50 terms)');
legend('5','15','50')

%plotting Dn
%n=[-10:10];
subplot(2,1,1),stem([fftshift(Dn)],'r','LineWidth',3,'MarkerSize',5), grid
xlabel('n');
ylabel('magnitude');
title('magnitude of Dn');
axis([-f0 (Ncoef+1)*f0 amin amax]);

subplot(2,1,2), stem([angle(Dn(1:NNNd))],'LineWidth',3,'MarkerSize',5), grid
xlabel('n');
ylabel('argument');
title('argument of Dn');
axis([-f0 (Ncoef+1)*f0 bmin bmax]);

Function m-files:
fourier_series_coef.m

function [a0, a, b]=fourier_series_coef(t,x,numterms)
[nrt nct]=size(t);
[nrx ncx]=size(x);

% Check for input errors
if (nrt~=nrx)|(nct~=ncx)
error('t and x must be the same size')
end

if min(nrt,nct)~=1
error('t and x must be row or column vectors')
end
N = length(t);

td = diff(t);
if any(td<0)
error('t must be increasing')
end
tdd=diff(td);

dt = t(2)-t(1);
T0 = t(N)-t(1);
f0 = 1/T0;
w0 = 2*pi*f0;

% a0 = 1/T0 * integ(x(t)) over T0

a0 = (1/T0)*trapz(t,x);

% am = 2/T0 * integ(x(t)*cos(m*w0*t)) over T0
% bm = 2/T0 * integ(x(t)*sin(m*w0*t)) over T0

a = zeros(numterms,1);
b = zeros(numterms,1);
for m=1:numterms
a(m) = (2/T0)*trapz(t,(x.*cos(m*w0*t)));
b(m) = (2/T0)*trapz(t,(x.*sin(m*w0*t)));
end

return

fourier_series_gen.m

function [x] = fourier_series_gen(t,T0,a0,a,b)
% generates a waveform using the partial sum of the fourier series

[nra nca]=size(a);
[nrb ncb]=size(b);
Na = length(a);
Nb = length(b);

x = a0 + zeros(size(t));
w0=2*pi/T0;
for m=1:Na
x = x + a(m)*cos(m*w0*t);
end
for m=1:Nb
x = x + b(m)*sin(m*w0*t);
end

return

rect_fcn.m

function y = rect_fcn(t)
% Continuous-time rect function
% y = 0.0 for t<-0.5 and t>+0.5,
% y = 1.0 for -0.5< t <+0.5
% y = 0.5 for |t| = 0.5

y = zeros(size(t));
y((t>-0.5)&(t<+0.5)) = 1.0;
y((t==-0.5)|(t==+0.5)) = 0.5;
return

Subject: Negative indices in arrays

From: Chris G

### Jojo (view profile)

(Chris G)

Date: 14 Jun, 2009 02:46:01

Message: 4 of 9

"Chris G" <n4cag@yahoo.com> wrote in message <h11nq9$73l$1@fred.mathworks.com>...

MADE A SLIGHT CORRECTION, but still same problem:

> Alright, welll. For an assignment I'm trying to calculate and plot the values for n for when they are zero and negative for the magnitude and phase plot at the very end of the Prob2.m for Dn. The negative indices are giving me the most difficulties :
>
> Prob2.m:
>
> clc
> clear all
> close all
> format compact
> %format short eng
>
>
> % Create a waveform from t=Tbegin to t=Tend
> Tbegin = 0.0;
> Tend = 5;
>
> N = 2^15; Nm1=N-1; Np1=N+1; Nd2=N/2;
>
> t=[0:Nm1]';
> t=Tbegin + t*Tend/Nm1;
> tsample = t(2)-t(1);
>
> T0 = (Tend - Tbegin);
> f0 = 1/T0;
> w0 = 2*pi*f0;
> fnyq = f0/2; wnyq=2*pi*fnyq;
>
> NNN=100;
>
> t1 = 2;
> x = ((-2*t).*(rect_fcn((t-1.5)/3)))+(rect_fcn((t-4)/2)) ;
> %x(t<=t1) = t(t<=t1);
>
> % evaluate the analytic expression
> n = 1:NNN;
> Dn = ((((exp(-j*n*(6/5)*pi)).*(2-(2*j*n*(6/5)*pi)))-2)./((n.^2)*(4/5)*(pi^2)))+(((exp(-j*n*2*pi))-(exp(-j*n*(6/5)*pi)))./(-j*n*2*pi));
>
>
> [a0,a,b]=fourier_series_coef(t,x,NNN);
> % Uncomment the following line to see the coeficients values.
> %a0, [a b];
>
> Dn2a = 2*real(Dn);
> Dn2b = -2*imag(Dn);
> % had to make N=2^10 larger at the beginning to get better
> % numerical integration results
> NNNd = 10;
> nnd=(1:NNNd);
>
> disp(' a_n coef ')
> [nnd' a(1:NNNd) Dn2a(1:NNNd)']
> disp(' ')
> disp(' b_n coef ')
> [nnd' b(1:NNNd) Dn2b(1:NNNd)']
> disp(' ')
> disp(' Dn')
> [nnd' Dn(1:NNNd).']
> disp(' ')
> disp(' |Dn|')
> [nnd' abs(Dn(1:NNNd))']
> disp(' ')
> disp(' arg(Dn)')
> [nnd' angle(Dn(1:NNNd))']
>
> % use the FFT to compute ~Dn
> XDn = fft(x)/N;
> disp(' ')
> disp(' ')
> disp(' analytic Dn FFT Dn')
> [Dn(1:NNNd).' XDn(2:NNNd+1)]
>
> % Generate a waveform using the Fourier Series
> xg = fourier_series_gen(t,T0,a0,a,b);
> subplot(2,1,1),plot(t,x), grid on
> ylabel('\it{x(t)}')
> title('One Period of \it{x(t)}');
>
> subplot(2,1,2), plot(t,xg), grid on
> xlabel('t (sec)')
> ylabel('\it{x^''(t)}');
> titlestr = ['Fourier Series Approximation to {\itx(t)} (' ...
> num2str(NNN) ' terms)'];
> title(titlestr);
>
> % Compare using partial sums of 5, 15 and 50 coeficients
>
> Np=3;
> tp=[0:(Np*N-1)]';
> tp=Tbegin + tp*Np*Tend/(Np*N-1);
>
> % 5
> Ncoef = 5;
> [a0,a,b]=fourier_series_coef(t,x,Ncoef);
> amin = min([a0; a]); amax = max([a0; a]);
> bmin = min(b); bmax = max(b);
> xg5 = fourier_series_gen(tp,T0,a0,a,b);
>
> % Plot Coefficients
> f = [f0:f0:(Ncoef*f0)]';
> figure
>
> % a's
> %subplot(2,1,1),stem([0; f],[a0; a],'r','LineWidth',3,'MarkerSize',5), grid
> %xlabel('f (Hz)');
> %ylabel('a_m');
> %title('Cosine Coefficients');
> %axis([-f0 (Ncoef+1)*f0 amin amax]);
> % b's
> %subplot(2,1,2), stem(f,b,'LineWidth',3,'MarkerSize',5), grid
> %xlabel('f (Hz)');
> %ylabel('b_m');
> %title('Sine Coefficients');
> %axis([-f0 (Ncoef+1)*f0 bmin bmax]);
>
> % 15
> Ncoef = 15;
> [a0,a,b]=fourier_series_coef(t,x,Ncoef);
> xg15 = fourier_series_gen(tp,T0,a0,a,b);
>
> % 50
> Ncoef = 50;
> [a0,a,b]=fourier_series_coef(t,x,Ncoef);
> xg50 = fourier_series_gen(tp,T0,a0,a,b);
> figure, plot(tp,xg5,tp,xg15,tp,xg50), grid on
> xlabel('t (sec)');
> ylabel('\it{x''(t)}')
> title('Partial Sum Approximations (5, 15, 50 terms)');
> legend('5','15','50')
>
>
> %plotting Dn
> %n=[-10:10];
> subplot(2,1,1),stem([abs(Dn)],'r','LineWidth',3,'MarkerSize',5), grid
> xlabel('n');
> ylabel('magnitude');
> title('magnitude of Dn');
> axis([-f0 (Ncoef+1)*f0 amin amax]);
>
> subplot(2,1,2), stem([angle(Dn(1:NNNd))],'LineWidth',3,'MarkerSize',5), grid
> xlabel('n');
> ylabel('argument');
> title('argument of Dn');
> axis([-f0 (Ncoef+1)*f0 bmin bmax]);
>
> Function m-files:
> fourier_series_coef.m
>
> function [a0, a, b]=fourier_series_coef(t,x,numterms)
> [nrt nct]=size(t);
> [nrx ncx]=size(x);
>
> % Check for input errors
> if (nrt~=nrx)|(nct~=ncx)
> error('t and x must be the same size')
> end
>
> if min(nrt,nct)~=1
> error('t and x must be row or column vectors')
> end
> N = length(t);
>
> td = diff(t);
> if any(td<0)
> error('t must be increasing')
> end
> tdd=diff(td);
>
> dt = t(2)-t(1);
> T0 = t(N)-t(1);
> f0 = 1/T0;
> w0 = 2*pi*f0;
>
> % a0 = 1/T0 * integ(x(t)) over T0
>
> a0 = (1/T0)*trapz(t,x);
>
> % am = 2/T0 * integ(x(t)*cos(m*w0*t)) over T0
> % bm = 2/T0 * integ(x(t)*sin(m*w0*t)) over T0
>
> a = zeros(numterms,1);
> b = zeros(numterms,1);
> for m=1:numterms
> a(m) = (2/T0)*trapz(t,(x.*cos(m*w0*t)));
> b(m) = (2/T0)*trapz(t,(x.*sin(m*w0*t)));
> end
>
> return
>
> fourier_series_gen.m
>
> function [x] = fourier_series_gen(t,T0,a0,a,b)
> % generates a waveform using the partial sum of the fourier series
>
> [nra nca]=size(a);
> [nrb ncb]=size(b);
> Na = length(a);
> Nb = length(b);
>
> x = a0 + zeros(size(t));
> w0=2*pi/T0;
> for m=1:Na
> x = x + a(m)*cos(m*w0*t);
> end
> for m=1:Nb
> x = x + b(m)*sin(m*w0*t);
> end
>
> return
>
> rect_fcn.m
>
> function y = rect_fcn(t)
> % Continuous-time rect function
> % y = 0.0 for t<-0.5 and t>+0.5,
> % y = 1.0 for -0.5< t <+0.5
> % y = 0.5 for |t| = 0.5
>
> y = zeros(size(t));
> y((t>-0.5)&(t<+0.5)) = 1.0;
> y((t==-0.5)|(t==+0.5)) = 0.5;
> return

Subject: Negative indices in arrays

From: Chris G

### Jojo (view profile)

(Chris G)

Date: 14 Jun, 2009 19:01:02

Message: 5 of 9

61 views and only one person has been able to help me? All I'm looking for is how to get Matlab to plot the negative indices for my array of numbers in Dn...

Subject: Negative indices in arrays

Date: 14 Jun, 2009 22:44:02

Message: 6 of 9

Hi Chris,

Why would you need non-positive indices? I could not go through your code exactly, so I will not be able to be specific about the problem. How about this simple example. Maybe it is clearer if we talk on this new small piece of code:

n = -10:0.5:10;
Dn = n.^2;

Now, we have Dn as a function of n. It is clear that length(n) is 41. So now, n(1) is -10, n(2) is -9.5, ..., n(41) = 10. Therefore, if you need the value of Dn at n = -9 for example, you can get it by Dn(3), right? Since n(3) = -9.

Please let me know if I understood your question correctly. If not, please give an example which is similar to the above one.

"Chris G" <n4cag@yahoo.com> wrote in message <h13hde$qlc$1@fred.mathworks.com>...
> 61 views and only one person has been able to help me? All I'm looking for is how to get Matlab to plot the negative indices for my array of numbers in Dn...

Subject: Negative indices in arrays

From: Kian

### Kian (view profile)

Date: 14 Jun, 2009 23:17:16

Message: 7 of 9

That's a lot of code for people to read through. You need to realize that some people are willing to help here, but it's your job to make it really easy for them. If you post a 100-line-long code and expect people to decode it and solve your issue then you might not get a response. I'm not being mean, but just trying to help.

Again, from what I understand, you're trying to plot a vector that goes from -10 to 10, right? Is it something like this:

x = -10:10;

And then you're trying to plot it? You never need negative indices. For example, imagine a Cartesian coordinate that goes from -10 to 10 for the x-axis in 1-unit steps:

-10 -9 -8 -7 ... -1 0 1 2 ... 7 8 9 10

OK? You don't have to start your indices from the middle. The beginning of the vector will be the most left number. In this case, your vector X will have the following values:

X = [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

X(1) = -10
X(11) = 0
X(21) = 10

Does this make sense? If not, please try to explain a bit more. Please give an example of what exactly it is that you're trying to do instead of posting the entire code. It's really hard to understand a long code that I haven't written and it's not formatted and color-coded in the .m form.

Kian

Subject: Negative indices in arrays

From: Kian

### Kian (view profile)

Date: 14 Jun, 2009 23:39:02

Message: 8 of 9

Seems like Sadik and I had the same take on your problem. I hope this is what you're looking for. If not, please explain more using either one of our examples. We talked about the same thing (I believe we posted at the same time).

Subject: Negative indices in arrays

From: Steven Lord

### Steven Lord (view profile)

Date: 15 Jun, 2009 01:16:34

Message: 9 of 9

"Chris G" <n4cag@yahoo.com> wrote in message
news:h11ecd$mps$1@fred.mathworks.com...
> Since matlab will not allow negative numbers or 0 of indices in arrays,
> how can I manipulate it to produce numbers for those negative indexes?
> I'm needing to calculate and plot on a stem plot an array going from -10
> to 10 for a specified equation.

Do you mean you want a plot like this?

x = -10:1:10;
y = x.^2;
stem(x, y)

Many plotting functions allow you to specify not only y but also x (and for
3D plotting functions, you can specify all of x, y, and z.)

--
Steve Lord
slord@mathworks.com