Matrix manipulation in Octave - matrix

I want to map a mX1 matrix X into mXp matrix Y where each row in the new matrix is as follows:
Y = [ X X.^2 X.^3 ..... X.^p]
I tried to use the following code:
Y = zeros(m, p);
for i=1:m
Y(i,:) = X(i);
for c=2:p
Y(i,:) = [Y(i,:) X(i).^p];
end
end

What you want do is called brodcasting. If you are using Octave 3.8 or later, the following will work fine:
octave> X = (1:5)'
X =
1
2
3
4
5
octave> P = (1:5)
P =
1 2 3 4 5
octave> X .^ P
ans =
1 1 1 1 1
2 4 8 16 32
3 9 27 81 243
4 16 64 256 1024
5 25 125 625 3125
The important thing to note is how X and P are a column and row vector respectively. See the octave manual on the topic.
For older of versions of Octave (without automatic broadcasting), the same can be accomplished with bsxfun (#power, X, P)

Related

Find the all possible multiples( size of n ) of a positive integer k

Input 1 :
64
Output:( size of 3 )
1 x 1 x 64 =64
1 x 2 x 32 =64
1 x 4 x 16 =64
1 x 8 x 8 =64
2 x 2 x 16 =64
2 x 4 x 8 =64
4 x 4 x 4 =64
Input 2 :
6
Output:( size of 2 )
1 x 6 =6
2 x 3 =6
I tried Using Complete Binary Tree but I didn't get all possible Combination
.
Here is :
64
32 2
16 2 2 1
8 2 1 2 1 2 1 1
If Your trace level by level elements only some combinations are available
64 x 1 X 1
32 X 2 X 1
16 x 2 x 2
8 x 2 x 2 x 2( limit > 3 )
Question is I need all possible combinations
You can use recursion method. Consider the following PHP code (I guess you can convert for the idea to each language you need):
function comb($num, $cnt, $prefix, $minDiv) {
if ($cnt == 0)
{
if ($num == 1)
return rtrim($prefix,",");
else return false;
}
$arrs = array();
for ($i=$minDiv; $i <= $num; $i++) {
if ($num % $i == 0) { // if num modulo i equal 0
$ans = comb($num/$i, $cnt-1, $prefix . $i . ",", $i );
if ($ans) // if valid combination add it
$arrs[] = $ans;
}
}
return $arrs;
}
$ans = comb(64,3, "",1);
echo "ANSWER:\n";
echo print_r($ans);
This code will generate the following answer for comb(6,2, "", 1):
1,6
2,3

Algorithms - Time complexity of recursive multiplication function

I had this as a test question to evaluate the time complexity of the below recursive method.
def multiply(x,y)
if y = 0:
return 0
z = multiply(x,y/2)
if y is even:
return 2z
else :
return x + 2z
I had written log(n) as the number y keeps decreasing by 2 and the recursive call will soon end as it meets the condition.
If the function is meant to have a zero check as stated above in the question, this function will never terminate.
Here is a working python version:
def multiply(x,y):
if y == 0:
return 0
z = multiply(x,y/2)
if y % 2 == 0:
return 2 * z
else :
return x + 2 * z
Whatever you feed into it: this will end in a recursion error. So complexity is infinite. Perhaps this is a trick question.
If however what your teacher meant was something like this:
def multiply(x, y):
if 0.01 > y > -0.01:
return 0
z = multiply(x, y / 2)
if y % 2 == 0:
return 2 * z
else:
return x + 2 * z
then complexity looks indeed like log(n).
Here is some complexity benchmarking code which counts the number of operations:
counter = 0
def multiply(x, y):
global counter
counter += 1
if 0.01 > y > -0.01:
return 0
z = multiply(x, y / 2)
if y % 2 == 0:
return 2 * z
else:
return x + 2 * z
for i in range(1000):
counter = 0
multiply(1, i)
print(i, counter)
It prints a sequence of numbers which is logarithmic in nature:
0 1
1 8
2 9
3 10
4 10
5 10
6 11
7 11
8 11
9 11
10 11
11 12
12 12
13 12
14 12
15 12
16 12
17 12
18 12
19 12
20 12
21 13
22 13
23 13
24 13
25 13
26 13
27 13
28 13
29 13
30 13
...

How to write a parallel loop in julia?

I have the following Julia code and I would like to parallelize it.
using DistributedArrays
function f(x)
return x^2;
end
y = DArray[]
#parallel for i in 1:100
y[i] = f(i)
end
println(y)
The output is DistributedArrays.DArray[]. I would like to have the value of y as follows: y=[1,4,9,16,...,10000]
You can use n-dimensional distributed array comprehensions:
First you need to add some more processes, either local or remote:
julia> addprocs(CPU_CORES - 1);
Then you must use DistributedArrays at every one of the spawned processes:
julia> #everywhere using DistributedArrays
Finally you can use the #DArray macro, like this:
julia> x = #DArray [#show x^2 for x = 1:10];
From worker 2: x ^ 2 = 1
From worker 2: x ^ 2 = 4
From worker 4: x ^ 2 = 64
From worker 2: x ^ 2 = 9
From worker 4: x ^ 2 = 81
From worker 4: x ^ 2 = 100
From worker 3: x ^ 2 = 16
From worker 3: x ^ 2 = 25
From worker 3: x ^ 2 = 36
From worker 3: x ^ 2 = 49
You can see it does what you expect:
julia> x
10-element DistributedArrays.DArray{Int64,1,Array{Int64,1}}:
1
4
9
16
25
36
49
64
81
100
Remember it works with an arbitrary number of dimensions:
julia> y = #DArray [#show i + j for i = 1:3, j = 4:6];
From worker 4: i + j = 7
From worker 4: i + j = 8
From worker 4: i + j = 9
From worker 2: i + j = 5
From worker 2: i + j = 6
From worker 2: i + j = 7
From worker 3: i + j = 6
From worker 3: i + j = 7
From worker 3: i + j = 8
julia> y
3x3 DistributedArrays.DArray{Int64,2,Array{Int64,2}}:
5 6 7
6 7 8
7 8 9
julia>
This is the most julian way to do what you intended IMHO.
We can look at macroexpand output in order to see what's going on:
Note: this output has been slightly edited for readability, T stands for:
DistributedArrays.Tuple{DistributedArrays.Vararg{DistributedArrays.UnitRange{DistributedArrays.Int}}}
julia> macroexpand(:(#DArray [i^2 for i = 1:10]))
:(
DistributedArrays.DArray(
(
#231#I::T -> begin
[i ^ 2 for i = (1:10)[#231#I[1]]]
end
),
DistributedArrays.tuple(DistributedArrays.length(1:10))
)
)
Which basically is the same as manually typing:
julia> n = 10; dims = (n,);
julia> DArray(x -> [i^2 for i = (1:n)[x[1]]], dims)
10-element DistributedArrays.DArray{Any,1,Array{Any,1}}:
1
4
9
16
25
36
49
64
81
100
julia>
Hi Kira,
I am new on Julia, but facing the same problem. Try this approach and see if it fits your needs.
function f(x)
return x^2;
end
y=#parallel vcat for i= 1:100
f(i);
end;
println(y)
Regards, RN

Selecting neighbours on a circle

Consider we have N points on a circle. To each point an index is assigned i = (1,2,...,N). Now, for a randomly selected point, I want to have a vector including the indices of 5 points, [two left neighbors, the point itself, two right neighbors].
See the figure below.
Some sxamples are as follows:
N = 18;
selectedPointIdx = 4;
sequence = [2 3 4 5 6];
selectedPointIdx = 1
sequence = [17 18 1 2 3]
selectedPointIdx = 17
sequence = [15 16 17 18 1];
The conventional way to code this is considering the exceptions as if-else statements, as I did:
if ii == 1
lseq = [N-1 N ii ii+1 ii+2];
elseif ii == 2
lseq = [N ii-1 ii ii+1 ii+2];
elseif ii == N-1
lseq=[ii-2 ii-1 ii N 1];
elseif ii == N
lseq=[ii-2 ii-1 ii 1 2];
else
lseq=[ii-2 ii-1 ii ii+1 ii+2];
end
where ii is selectedPointIdx.
It is not efficient if I consider for instance 7 points instead of 5. What is a more efficient way?
How about this -
off = -2:2
out = mod((off + selectedPointIdx) + 17,18) + 1
For a window size of 7, edit off to -3:3.
It uses the strategy of subtracting 1 + modding + adding back 1 as also discussed here.
Sample run -
>> off = -2:2;
for selectedPointIdx = 1:18
disp(['For selectedPointIdx =',num2str(selectedPointIdx),' :'])
disp(mod((off + selectedPointIdx) + 17,18) + 1)
end
For selectedPointIdx =1 :
17 18 1 2 3
For selectedPointIdx =2 :
18 1 2 3 4
For selectedPointIdx =3 :
1 2 3 4 5
For selectedPointIdx =4 :
2 3 4 5 6
For selectedPointIdx =5 :
3 4 5 6 7
For selectedPointIdx =6 :
4 5 6 7 8
....
For selectedPointIdx =11 :
9 10 11 12 13
For selectedPointIdx =12 :
10 11 12 13 14
For selectedPointIdx =13 :
11 12 13 14 15
For selectedPointIdx =14 :
12 13 14 15 16
For selectedPointIdx =15 :
13 14 15 16 17
For selectedPointIdx =16 :
14 15 16 17 18
For selectedPointIdx =17 :
15 16 17 18 1
For selectedPointIdx =18 :
16 17 18 1 2
You can use modular arithmetic instead: Let p be the point among N points numbered 1 to N. Say you want m neighbors on each side, you can get them as follows:
(p - m - 1) mod N + 1
...
(p - 4) mod N + 1
(p - 3) mod N + 1
(p - 2) mod N + 1
p
(p + 1) mod N + 1
(p + 2) mod N + 1
(p + 3) mod N + 1
...
(p + m - 1) mod N + 1
Code:
N = 18;
p = 2;
m = 3;
for i = p - m : p + m
nb = mod((i - 1) , N) + 1;
disp(nb);
end
Run code here
I would like you to note that you might not necessarily improve performance by avoiding a if statement. A benchmark might be necessary to figure this out. However, this will only be significant if you are treating tens of thousands of numbers.

Obtaining opposite diagonal of a matrix in Matlab

Let A be an matrix of size [n,n]. If I want to extract its diagonal, I do diag(A).
Actually, I want the opposite diagonal, which would be [A(n,1),A(n-1,2),A(n-2,3),...].
One way to do this is via diag(flipud(A)). However, flipud(A) is quite wasteful and multiplies the time it takes by a factor of 10 compared to finding the usual diagonal.
I'm looking for a fast way of obtaining the opposite diagonal. Naturally, for loops seem abysmally slow. Suggestions would be greatly appreciated.
Here is my matrix, produced by A = magic(5)
A =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
s = size(A,1)
A(s:s-1:end-1)
ans =
11 12 13 14 15
Below is a comparison of all the methods mentioned so far, plus a few other variations I could think of. This was tested on 64-bit R2013a using TIMEIT function.
function [t,v] = testAntiDiag()
% data and functions
A = magic(5000);
f = {
#() func0(A) ;
#() func1(A) ;
#() func2(A) ;
#() func3(A) ;
#() func4(A) ;
#() func5(A) ;
#() func6(A) ;
#() func7(A) ;
};
% timeit and check results
t = cellfun(#timeit, f, 'UniformOutput',true);
v = cellfun(#feval, f, 'UniformOutput',false);
assert( isequal(v{:}) )
end
function d = func0(A)
d = diag(A(end:-1:1,:));
end
function d = func1(A)
d = diag(flipud(A));
end
function d = func2(A)
d = flipud(diag(fliplr(A)));
end
function d = func3(A)
d = diag(rot90(A,3));
end
function d = func4(A)
n = size(A,1);
d = A(n:n-1:end-1).';
end
function d = func5(A)
n = size(A,1);
d = A(cumsum(n + [0,repmat(-1,1,n-1)])).';
end
function d = func6(A)
n = size(A,1);
d = A(sub2ind([n n], n:-1:1, 1:n)).';
end
function d = func7(A)
n = size(A,1);
d = zeros(n,1);
for i=1:n
d(i) = A(n-i+1,i);
end
end
The timings (in the same order they are defined above):
>> testAntiDiag
ans =
0.078635867152801
0.077895631970976 % #AlexR.
0.080368641824528
0.195832501156751
0.000074983294297 % #thefourtheye
0.000143019460665 % #woodchips
0.000174679680437
0.000152488508547 % for-loop
The most suprising result to me is the last one. Apparently JIT compilation is very effective on such simple for-loops.
The elements you want are easily obtained by indexing. For example, this should do the trick.
n = 4;
A = magic(n)
A =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
A(cumsum(n + [0,repmat(-1,1,n-1)]))
ans =
4 7 10 13
I could also have used sub2ind to get those element indexes, but this does it a bit more cleanly, though less obvious in how it works.
A = magic(6)
A =
35 1 6 26 19 24
3 32 7 21 23 25
31 9 2 22 27 20
8 28 33 17 10 15
30 5 34 12 14 16
4 36 29 13 18 11
b = diag(A(1:length(A),length(A):-1:1))
b =
24
23
22
33
5
4

Resources