Simplify the looping under two sets of conditions - matlab

I want to establish a pair of indices =[row col] where
row = 4 * (n-1) + i and col = 4 * (m-1) + i
Explanation for i, m and n:
For n = 1 and m = 2, 3, 4, loop i = 1 : 4.
For n = 2 and m = 1, loop i = 1 : 4.
For n = 3 and m = 5, loop i = 1 : 4.
The outcome should be:
row = [1 1 1 2 2 2 3 3 3 4 4 4 5 6 7 8 9 10 11 12]
col = [5 9 13 6 10 14 7 11 15 8 12 16 1 2 3 4 17 18 19 20]
That is, I want to establish pairs of indices under different sets of n-m conditions.
My trial:
row = []; col = [];
n = 1;
for i = 1 : 4
for m = [2 3 4]
row = [row 4 * (n - 1) + i];
col = [col 4 * (m - 1) + i];
end
end
n = 2; m = 1;
for i = 1 : 4
row = [row 4 * (n - 1) + i];
col = [col 4 * (m - 1) + i];
end
n= 3; m = 5;
for i = 1 : 4
row = [row 4 * (n - 1) + i];
col = [col 4 * (m - 1) + i];
end
This works but indeed I have many n-m conditions and the looping for i = 1 : 4 appeared repeatedly which seems that can be simplified.
May I know if there are any elegant solutions to finish my objective?
I appreciate for your help.

You can use a bsxfun based solution for all those three cases -
ii = 1:4
row = reshape(bsxfun(#(A,B) 4 * (B-1) + A,ii,n'),1,[]) %//'
col = reshape(bsxfun(#(A,B) 4 * (B-1) + A,ii,m'),1,[]) %//'
The inputs would be as listed next.
Case #1:
m = [2, 3, 4]
n = ones(1,numel(m))
Case #2:
n = 2
m = 1
Case #3:
n = 3
m = 5

I would create a Matrix with all parameters, then apply the math once:
M=[...n m i
ones(3,1) (2:4).' (1:3).';...
2*ones(4,1) ones(4,1) (1:4).';...
3*ones(4,1) 5*ones(4,1) (1:4).';...
];
row = (4 * (M(:,1) - 1) + M(:,3)).';
col = (4 * (M(:,2) - 1) + M(:,3)).';
%alternative:
%index=(4 * (M(:,[1:2]) - 1) + M(:,[3,3])).'

Related

Sum of elements with a loop

I have to calculate the sum of a vector
v = [5 2 6 8 1 2];
by using a loop. I have tried this
v = [5 2 6 8 1 2];
i = 0;
for i = 1:6
v1 = sum(v(i))
i = i + 1;
end
But I cant get it to work. It to choose the first vector and then add it to the second.
v = [5 2 6 8 1 2];
sumValue = 0;
for vals = 1:length(v)
sumValue = sumValue + v(vals);
end
disp(sumValue)

How to generate matrix in MATLAB where values decrease with increasing coordinates

I'm trying to generate an n x n matrix like
5 4 3 2 1
4 4 3 2 1
3 3 3 2 1
2 2 2 2 1
1 1 1 1 1
where n = 5 or n 50. I'm at an impasse and can only generate a portion of the matrix. It is Problem 2.14 from Numerical Methods using MATLAB 3rd Edition by Penny and Lindfield. This is the best I have so far:
n = 5;
m = n;
A = zeros(m,n);
for i = 1:m
for j = 1:n
A(i,j) = m;
end
m = m - 1;
end
Any feedback is appreciated.
That was a nice brain-teaser, here’s my solution:
[x,y] = meshgrid(5:-1:1);
out = min(x,y)
Output:
ans =
5 4 3 2 1
4 4 3 2 1
3 3 3 2 1
2 2 2 2 1
1 1 1 1 1
Here's one loop-based approach:
n = 5;
m = n;
A = zeros(m, n);
for r = 1:m
for c = 1:n
A(r, c) = n+1-max(r, c);
end
end
And here's a vectorized approach (probably not faster, just for fun):
n = 5;
A = repmat(n:-1:1, n, 1);
A = min(A, A.');
That's one of the matrices in Matlab's gallery, except that it needs a 180-degree rotation, which you can achieve with rot90:
n = 5;
A = rot90(gallery('minij', n), 2);

Replace rows having at least one duplicate number or one zero by a user defined row

I have a matrix having rows with repeated numbers.
A= [ 2 3 6;
4 7 4;
8 7 2;
1 3 1;
7 8 2 ]
The codes below find those rows and replace them with a Dummy_row [1 2 3]
new_A=[ 2 3 6;
1 2 3;
8 7 2;
1 2 3;
7 8 2 ]
This are the codes:
CODE NUMBER 1 (#Bruno)
Dummy_row = [1 2 3];
b = any(~diff(sort(A,2),1,2),2);
A(b,:) = repmat(Dummy_row,sum(b),1)
CODE NUMBER 2 (#Kamtal)
Dummy_row = [1 2 3];
b = diff(sort(A,2),1,2);
b = sum(b == 0,2);
b = b > 0;
c = repmat(Dummy_row,sum(b),1);
b = b' .* (1:length(b));
b = b(b > 0);
newA = A;
newA(b,:) = c
Note: both codes Number 1 and 2 perform the task efficiently.
Question
How can this code(either code num 1 or num 2) be modified such that it also replaces any rows having at least one zero with the Dummy_row?
Code 1
b = any(~diff(sort(A,2),1,2),2) | any(A==0,2); % <-- Only change
A(b,:) = repmat(Dummy_row,sum(b),1);
Code 2
b = diff(sort(A,2),1,2);
b = sum(b == 0,2);
b = (b > 0) | any(A==0,2); % <-- Only change
c = repmat(Dummy_row,sum(b),1);
b = b' .* (1:length(b));
b = b(b > 0);
newA = A;
newA(b,:) = c;
By the way: Code1 basically does the same thing that Code2 does, just that it uses logical-indexing instead of doing the unnecessary conversion from logical indexes to index positions.

specific tuples generation and counting (matlab)

I need to generate (I prefere MATLAB) all "unique" integer tuples k = (k_1, k_2, ..., k_r) and
its corresponding multiplicities, satisfying two additional conditions:
1. sum(k) = n
2. 0<=k_i<=w_i, where vector w = (w_1,w_2, ..., w_r) contains predefined limits w_i.
"Unique" tuples means, that it contains unique unordered set of elements
(k_1,k_2, ..., k_r)
[t,m] = func(n,w)
t ... matrix of tuples, m .. vector of tuples multiplicities
Typical problem dimensions are about:
n ~ 30, n <= sum(w) <= n+10, 5 <= r <= n
(I hope that exist any polynomial time algorithm!!!)
Example:
n = 8, w = (2,2,2,2,2), r = length(w)
[t,m] = func(n,w)
t =
2 2 2 2 0
2 2 2 1 1
m =
5
10
in this case exist only two "unique" tuples:
(2,2,2,2,0) with multiplicity 5
there are 5 "identical" tuples with same set of elements
0 2 2 2 2
2 0 2 2 2
2 2 0 2 2
2 2 2 0 2
2 2 2 2 0
and
(2,2,2,1,1) with multiplicity 10
there are 10 "identical" tuples with same set of elements
1 1 2 2 2
1 2 1 2 2
1 2 2 1 2
1 2 2 2 1
2 1 1 2 2
2 1 2 1 2
2 1 2 2 1
2 2 1 1 2
2 2 1 2 1
2 2 2 1 1
Thanks in advance for any help.
Very rough (extremely ineffective) solution. FOR cycle over 2^nvec-1 (nvec = r*maxw) test samples and storage of variable res are really terrible things!!!
This solution is based on tho following question.
Is there any more effective way?
function [tup,mul] = tupmul(n,w)
r = length(w);
maxw = max(w);
w = repmat(w,1,maxw+1);
vec = 0:maxw;
vec = repmat(vec',1,r);
vec = reshape(vec',1,r*(maxw+1));
nvec = length(vec);
res = [];
for i = 1:(2^nvec - 1)
ndx = dec2bin(i,nvec) == '1';
if sum(vec(ndx)) == n && all(vec(ndx)<=w(ndx)) && length(vec(ndx))==r
res = [res; vec(ndx)];
end
end
tup = unique(res,'rows');
ntup = size(tup,1);
mul = zeros(ntup,1);
for i=1:ntup
mul(i) = size(unique(perms(tup(i,:)),'rows'),1);
end
end
Example:
> [tup mul] = tupmul(8,[2 2 2 2 2])
tup =
0 2 2 2 2
1 1 2 2 2
mul =
5
10
Or same case but with changed limits for first two positions:
>> [tup mul] = tupmul(8,[1 1 2 2 2])
tup =
1 1 2 2 2
mul =
10
This is far more better algorithm, created by Bruno Luong (phenomenal MATLAB programmer):
function [t, m, v] = tupmul(n, w)
v = tmr(length(w), n, w);
t = sort(v,2);
[t,~,J] = unique(t,'rows');
m = accumarray(J(:),1);
end % tupmul
function v = tmr(p, n, w, head)
if p==1
if n <= w(end)
v = n;
else
v = zeros(0,1);
end
else
jmax = min(n,w(end-p+1));
v = cell2mat(arrayfun(#(j) tmr(p-1, n-j, w, j), (0:jmax)', ...
'UniformOutput', false));
end
if nargin>=4 % add a head column
v = [head+zeros(size(v,1),1,class(head)) v];
end
end %tmr

Matlab Vectorization : How to avoid this "for" loop?

I have following matrices :
X=1 2 3
Y=4 5 6
A=1 2 3
4 5 6
7 8 9
I Want to do
for each (i,j) in A
v = A(i,j)*X - Y
B(i,j) = v * v'
i.e. each element of A is multiplied by vector X, then resultant vector subtracts Y from itself and finally we take inner product of that vector to bring a single number.
Can it be done without for loop ?
One thing often forgotten in Matlab: The operator ' takes the conjugate transposed (.' is the ordinary transposed). In other words, A' == conj(trans(A)), whereas A.' == trans(A), which makes a difference if A is a complex matrix.
Ok, let's apply some mathematics to your equations. We have
v = A(i,j)*X - Y
B(i,j) = v * v'
= (A(i,j)*X - Y) * (A(i,j)*X - Y)'
= A(i,j)*X * conj(A(i,j))*X' - Y * conj(A(i,j))*X'
- A(i,j)*X * Y' + Y * Y'
= A(i,j)*conj(A(i,j)) * X*X' - conj(A(i,j)) * Y*X' - A(i,j) * X*Y' + Y*Y'
So a first result would be
B = A.*conj(A) * (X*X') - conj(A) * (Y*X') - A * (X*Y') + Y*Y'
In the case of real matrices/vectors, one has the identities
X*Y' == Y*X'
A == conj(A)
which means, you can reduce the expression to
B = A.*A * (X*X') - 2*A * (X*Y') + Y*Y'
= A.^2 * (X*X') - 2*A * (X*Y') + Y*Y'
An alternative method:
X = [1 2 3]
Y = [4 5 6]
A = [1 2 3; 4 5 6; 7 8 9]
V = bsxfun(#minus, A(:)*X, [4 5 6])
b = sum((V.^2)')
B = reshape(b , 3, 3)
I get the result:
B = 27 5 11
45 107 197
315 461 635