An easy? Matlab Problem involving matrices

  • Thread starter Thread starter alba_ei
  • Start date Start date
  • Tags Tags
    Matlab Matrices
AI Thread Summary
The discussion revolves around solving a MATLAB problem involving matrices and the use of the prod function. The original code presented was inefficient, relying on a for loop to calculate Sn, which was improved by using matrix operations. The revised solution employs the repmat function to create larger matrices for x and n, allowing for vectorized calculations that enhance performance. The final code effectively calculates Sn, S_inf, and e_n while emphasizing the importance of clean coding practices. Overall, the thread highlights the benefits of matrix operations in MATLAB for efficiency and clarity.
alba_ei
Messages
38
Reaction score
1

Homework Statement


2ztdb12.png


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?
 
Physics news on Phys.org
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.
 
Back
Top