Write a MATLAB program for compute the value of following function using normal method, avoid inner loop, avoid both loop

Write a MATLAB program for compute the value of following function using normal method, avoid inner loop, avoid both loop

Code:

 

Method1:


clc
clear;
 y = zeros(20,1);
y(1) = 1;
temp=0;
for n = 2:20
for m = 1:n
        temp = temp + m^3;
end
    y(n) = y(n-1)*temp;
    temp = 0;
end
disp('y(1)');
disp(y(1));
disp('y(2)');
disp(y(2));
disp('y(3)');
disp(y(3));

Method 2

(avoid inner loop):

clc
clear;
 y = zeros(20,1);
y(1) = 1;
for n = 2:20
    temp = 1:n;
    y(n) = y(n-1)*sum(temp.^3);
end
disp('y(1)');
disp(y(1));
disp('y(2)');
disp(y(2));
disp('y(3)');
disp(y(3));

 

Method 3

(avoid both loop):

clc
clear;
X = tril(ones(20)*diag(1:20));
x = sum(X.^3,2);
Y = tril(ones(20)*diag(x))+...
triu(ones(20)) - eye(20);
y = prod(Y,2);
disp('y(1)');
disp(y(1));
disp('y(2)');
disp(y(2));
disp('y(3)');
disp(y(3));

 

 


Output:


No comments

Powered by Blogger.