An easy? Matlab Problem involving matrices

3 replies · 3K views · last reply
alba_ei
Messages
38
Reaction score
1

Homework Statement


Typeset problem 2.11: product S_N of (1 - x^2/(n^2 - a^2)) for n from 1 to N, with S_inf given as a/sqrt(a^2+x^2) times sin(pi sqrt(a^2+x^2)) over sin(pi a), and percentage error e_N defined as 100 times (S_N - S_inf)/S_inf.


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?
 
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
 
Your best bet is to use matrices instead of a for loop.

Code:
% 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
 
RoshanBBQ said:
Your best bet is to use matrices instead of a for loop.

Code:
% 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

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.