How can I vectorize the following calculation? - matlab

Suppose there is a value n input from a user and it goes in to the following for loop code. Is there a way to vectorize the following code?
A = 1:n
B = [1 1;1 1]
for i = 1:n
B = B + A(i)*B;
end

Let's have a look at a specific example:
n = 5;
A = 1:n;
B = [1 1; 1 1];
for i = 1:n
B = B + A(i) * B;
end
B
The result is:
B =
720 720
720 720
First of all, I would re-write the loop:
n = 5;
A = 1:n;
B = [1 1; 1 1];
for i = 1:length(A)
B = B * (A(i) + 1);
end
B
That way, it's more obvious, that your loop variable i simply iterates all elements in A.
Also: B + A(i) * B is the same as B * (A(i) + 1).
Now, we see, that inside the loop, you're basically calculating:
B = B * (A(1) + 1) * (A(2) + 1) * (A(3) + 1) ...
The product over all elements in A (or here: A + 1) can be simplified by using MATLAB's prod function:
n = 5;
A = 1:n;
B = [1 1; 1 1];
B = B * prod(A + 1)
Let's check the result:
B =
720 720
720 720
In that very special case for A = 1:n, the product prod(A + 1) is simply the factorial of n + 1, such that we could also use MATLAB's factorial function:
n = 5;
B = [1 1; 1 1];
B = B * factorial(n + 1)

Related

Remove table rows based on condition in matlab

a=[1; 2 ; 3]; b=[ 4; 5; 6 ]; T=table(a,b).
I want to remove rows of table for which the value of b is less than or equal to 5 (b<=5).
You can use logical indexing:
a=[1; 2 ; 3];
b=[ 4; 5; 6 ];
T=table(a,b);
rowidx = (T.b <= 5);
T = T(~rowidx, :);
Which returns:
T =
1×2 table
a b
_ _
3 6
Fast, simple. elegant:
T(T.b <= 5,:) = [];
Another approach:
a = [1; 2; 3];
b = [4; 5; 6];
X = [a, b];
n = 1; m = 1;
while (n <= size(X, 1))
if(X(n, 2) > 5)
X_new(m, :) = X(n, :);
m = m + 1;
end
n = n + 1;
end
'X_new' will be the required matrix.

adding consecutive numbers in a vector in matlab

i have a vector and a scalar as input in a problem , the problem is to compute the largest product of n consecutive number of the vector and output the product and the index of the element of the vector that is the first term of the product.
E.g vector =[ 1 2 3 4 5 6] , n=3
I'm supposed to get '3' (i e n) consecutive number of vector whose product is the largest .
in this case it will be 4*5*6
so output will be 120 and 4 as the index.
now if vector has fewer than 'n' elements, the function outputon returns 0 and -1 as the output.
please i need ideas on how to achieve this
You can make a simple implementation with loops:
a = [1 2 3 4 5 6]
w = 3
n = length(a)
maximum = -1
for i = 1:n-w
p = prod(a(i:i+w))
if (p > maximum)
maximum = p
end
end
maximum
Or, you can use the nlfilter from the image processing palette.
a = []
w = 3
if (length(a) >= w)
products = nlfilter(a, [1 w], #(x) prod(x))
res = max(products)
else
res = -1
end
You can create the moving window from the answer of raryeng for the question Matrix with sliding window elements and then appyl cumprod on the columns and take the max with its index.
myvec = [1 2 2 1 3 1];
n = 3;
ind = bsxfun(#plus, 1:n, (0:1:length(myvec)-n).')';
M = cumprod(myvec(ind));
[val,its_ind] = max(M(end,:));
You can encapsulate this with an if condition checking whether the length of myvec is larger than
You can compute the element-wise logarithm of your vector, so multiplication becomes addition; and sliding addition is just convolution with a window of ones:
function [m, p] = f(v, n)
if numel(v) < n
m = -1;
p = 0;
else
c = conv(log(v(:)), ones(n,1), 'valid'); % convolution with vector of n ones
[~, m] = max(c); % starting index of maximizing window
p = prod(v(m+(0:n-1))); % corresponding product
end
Examples:
>> v = [1 2 3 4 5 6]; n = 3;
>> [m, p] = f(v,n)
m =
4
p =
120
>> v = [1 2 3 4 5 6]; n = 7;
>> [m, p] = f(v,n)
m =
-1
p =
0
>> v = [1 4 6 2 5 3]; n = 3;
>> [m, p] = f(v,n)
m =
3
p =
60

Matrix Basis expansion

MATLAB:
I am trying to do basis expansion of a huge matrix(1000x15).
For example,
X =
x1 x2
1 4
2 5
3 6
I want to build a new matrix.
Y =
x1 x2 x1*x1 x1*x2 x2*x2
1 4 1 4 16
2 5 4 10 25
3 6 9 18 36
Could any one please suggest a easier way to do this
% your input
A = [1 4; 2 5; 3 6];
% generate pairs
[p,q] = meshgrid(1:size(A,2), 1:size(A,2));
% only retain unique pairs
ii = tril(p) > 0;
% perform element wise multiplication
res = [A A(:,p(ii)) .* A(:,q(ii))];
Using the one-liner from this answer to get the 2-combinations of the indices, you can generate the matrix without the interleaved ordering with
function Y = columnCombo(Y)
comb = nchoosek(1:size(Y,2),2);
Y = [Y , Y.^2 , Y(:,comb(:,1)).*Y(:,comb(:,2))];
end
For the interleaved ordering, I came up with this, possibly sub-optimal, solution:
function Y = columnCombo(Y)
[m,n] = size(Y);
comb = nchoosek(1:n,2);
Y = [Y,zeros(m,n + size(comb,1))];
col = n+1;
for k = 1:n-1
Y(:,col) = Y(:,k).*Y(:,k) ;
ms = comb(comb(:,1)==k,:) ;
ncol = size(ms,1) ;
Y(:,col+(1:ncol)) = Y(:,ms(:,1)).*Y(:,ms(:,2)) ;
col = col + ncol + 1 ;
end
Y(:,end) = Y(:,n).^2;
end

Matlab: Block Tridiagonal with Non-Square Vectors

I'm trying to create a diagonal matrix using the following matrix as the diagonal
base = [a b c d e f 0;
0 g h i j k l];
I need the resulting matrix to look like this...
[a b c d e f 0 0 0;
0 g h i j k l 0 0;
0 0 a b c d e f 0;
0 0 0 g h i j k l];
except it needs to be "n" elements tall
I have tried using the kron function, but it shifts each consecutive row too many elements to the right.
How can I accomplish what I need in a way where I can select n arbitrarily?
You can do it pretty fast with a 2D convolution:
n = 4; %// desired number of rows in result. Should be a multiple of size(base,1)
T = eye(n-1);
T(2:size(base,1):end,:) = 0;
result = conv2(base,T);
Example: with
base =
0.7497 0.3782 0.4470 0.5118 0.6698 0.3329 0
0 0.9850 0.5638 0.9895 0.4362 0.4545 0.8578
and n=4 the result is
result =
0.7497 0.3782 0.4470 0.5118 0.6698 0.3329 0 0 0
0 0.9850 0.5638 0.9895 0.4362 0.4545 0.8578 0 0
0 0 0.7497 0.3782 0.4470 0.5118 0.6698 0.3329 0
0 0 0 0.9850 0.5638 0.9895 0.4362 0.4545 0.8578
The easy way is to use repeated out-of-bounds assignment. MATLAB will automatically pad any missing entries with 0 in those cases. Here's how:
%// Some test variables
a = rand; g = rand;
b = rand; h = rand;
c = rand; i = rand;
d = rand; j = rand;
e = rand; k = rand;
f = rand; l = rand;
%// base matrix
base = [
a b c d e f 0;
0 g h i j k l];
%// use out-of-bounds assignment
n = 3;
output = base;
for ii = 1:n
output(end+1:end+size(base,1), size(base,1)*ii+1:end+size(base,1)) = base;
end
The hard way is the faster way (relevant for when n is large and/or you need to repeat this very often). Figure out the pattern behind which indices would be filled in the final matrix by which values in the original matrix, then generate a list of those indices and assign those values to those indices:
[b1,b2] = size(base);
[ii,jj,vv] = find(base);
inds = bsxfun(#plus, (ii + (n+1)*b1*(jj-1)).', (0:n).'*b1*(1 + (n+1)*b1));
output = zeros( (n+1)*b1, b2+n*b1 );
output(inds) = repmat(vv.', n+1, 1)
I'll leave it as an exercise for you to figure out what happens here exactly :)

Difference between skewness function and skewness formula result

Consider the matrix
c =
1 2
3 4
m = 2;
n = 2;
% mean
% sum1 = uint32(0);
b4 = sum(c);
b5 = sum(b4');
c5 = b5 / ( m * n )
% standard deviation
sum2 = uint32(0);
for i = 1 : m
for j = 1 : n
b = ( double(c(i,j)) - c5 ) ^ 2 ;
sum2 = sum2 + b ;
end
end
sum3 = sum2 / ( m * n );
std_dev = sqrt(double(sum3))
% skewness
sum9 = 0;
for i = 1 : m
for j = 1 : n
skewness_old = ( ( double(c(i,j)) - c5 ) / ( std_dev) )^ 3 ;
sum9 = sum9 + skewness_old ;
end
end
skewness_new = sum9 / ( m * n )
The skewness result is 0
If I use the matlab function skewness,
skewness(c)
c =
1 2
3 4
skewness(c)
ans =
0 0
Why is the function skewness returning two 0's, While the formula returns only one 0
MATLAB function SKEWNESS by default calculates skewness for each column separately. For the whole matrix do skewness(c(:)).