# An easy? Matlab Problem involving matrices

1. May 24, 2012

### alba_ei

1. The problem statement, all variables and given/known data

3. The attempt at a solution
%2.11
x=1:0.5:5; a=sqrt(2.8);
n=[1:1:100];
Sn=prod(1-(x.^2)./(n.^2-a^2));
S_inf=(a/sqrt(a^2+x.^2)).*sin(pi*sqrt(a^2+x.^2))/sin(pi*a);
e_n=100*(Sn-S_inf)./S_inf

I know I can't use ./ if the two matrices are different, meaning x./n.
How do I use the prod function without going through this issue?

2. May 25, 2012

### jimep

Your best bet is to iterate through the Sn with x.

I've written a bit of code here, its the worst code possible, a programmer might murder me if they would get a look at this but it solves the problem.

Now go and write clean code;

%2.11
clear all;
clc;
a=sqrt(2.8);
n=1:1:100;
X=1:0.5:5;
i=1;

for x=1:0.5:5
Sn(i) = prod(1-(x^2./(n.^2-a^2)));
i=i+1;
end

S_inf=(a./sqrt(a^2+X.^2)).*(sin(pi*sqrt(a^2+X.^2))./sin(pi*a));

e_n=((Sn-S_inf)./S_inf)*100

3. May 25, 2012

### RoshanBBQ

Your best bet is to use matrices instead of a for loop.

Code (Text):
% define input
N = 100;
x = 1:0.5:5;
a = sqrt(2.8);

% Create big matrices
X = repmat(x, [N,1]);
n = repmat( (1:N).' ,[1,length(x)]);

% Calculate Sn
SN = prod(1-X.^2./(n.^2-a^2));

% Calculate inf values
Sinf = a./sqrt(a^2+x.^2).*sin(pi()*sqrt(a^2+x.^2))/sin(pi()*a);

% Caclulate eN
eN = 100*(SN-Sinf)./Sinf

4. May 25, 2012

### jimep

Yess! This is much nicer. I also feel that I have to apologize for my 'best bet' part.
I just thought that less computation time would be more efficient.