performance - What is the fast way to calculate this summation in MATLAB? -
so have next constraints:
how write in matlab in efficient way? inputs x_mn
, m
, , n
. set b={1,...,n}
, set u={1,...,m}
i did (because write x
follwoing vector)
x=[x_11, x_12, ..., x_1n, x_21, x_22, ..., x_m1, x_m2, ..., x_mn]
:
%# first constraint function r1 = constraint_1(m, n) ee = eye(n); r1 = zeros(n, n*m); m = 1:m r1(:, (m-1)*n+1:m*n) = ee; end end %# sec constraint function r2 = constraint_2(m, n) ee = ones(1, n); r2 = zeros(m, n*m); m = 1:m r2(m, (m-1)*n+1:m*n) = ee; end end
by above code matrix a=[r1; r2]
0-1
, have a*x<=1
.
for example, m=n=2
, have this:
and, create function test(x)
returns true or false according x
.
i help , optimize code.
you should place x_mn
values in matrix. after that, can sum in each dimension want. looking @ constraints, place these values in m x n
matrix, m
amount of rows , n
amount of columns.
you can place values in vector , build summations in way intended earlier, have write for
loops subset proper elements in each iteration, inefficient. instead, utilize matrix, , utilize sum
sum on dimensions want.
for example, let's values of x_mn
ranged 1 20. b
in set 1
5
, u
in set 1
4
. such:
x = vec2mat(1:20, 5) x = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
vec2mat
takes vector , reshapes matrix. specify number of columns want sec element, , create right amount of rows ensure proper matrix built. in case, want 5 columns, should create 4 x 5
matrix.
the first constraint can achieved doing:
first = sum(x,1) first = 34 38 42 46 50
sum
works vectors matrices. if have matrix supplied sum
, can specify sec parameter tells in direction wish sum. in case, specifying 1
sum on of rows each column. works in first dimension, rows.
what doing is summing on possible values in set b
on values of u
, doing here. summing every single column individually.
the sec constraint can achieved doing:
second = sum(x,2) sec = 15 40 65 90
here specify 2
sec parameter can sum on of columns each row. sec dimension goes on columns. doing is summing on possible values in set u
on values of b
. basically, summing every single row individually.
btw, code not achieving think it's achieving. you're doing replicating identity matrix set number of times on groups of columns in matrix. not performing summations per constraint. doing ensuring matrix have conditions specified @ origin of post enforced. these ideal matrices required satisfy constraints.
now, if want check see if first status or sec status satisfied, can do:
%// first status satisfied? firstsatisfied = all(first <= 1); %// sec status satisfied secondsatisfied = all(second <= 1);
this check every element of first
or second
, see if resulting sums after above code showed <= 1
. if satisfy constraint, have true
. else, have false
.
please allow me know if need further.
performance matlab optimization