I have the following objective function:
I am not sure how to write it in cvx.
This is my try:
cvx_begin sdp
variable Q(T,n,N)
%variable X_0T*Q(:,:,N) symmetric
obj = trace(X_0T*Q(:,:,N));
for j = 1:N-1
obj= obj + trace(X_0T*Q(:,:,j)))
subject to
[X_0T*Q(:,:,j+1)-eye(n), X_1T*Q(:,:,j); Q(:,:,j)'*X_1T', X_0T*Q(:,:,j)] >= 0;
X_0T*Q(:,:,1) >= eye(n);
end
minimize(obj)
cvx_end
K_cvx_df = -U_01T*Q(:,:,N)*pinv(X_0T*Q(:,:,N))
However, when I try to solve it for N going to infinity, it gives me a different solution from the infinite time horizon case, which is
cvx_begin sdp
variable Q(T,n)
minimize( trace(X_0T*Q))
subject to
[X_0T*Q-eye(n), X_1T*Q; Q'*X_1T', X_0T*Q] >= 0
cvx_end
K_cvx_d = -U_01T*Q*inv(X_0T*Q)
Related
Update: I completely overlooked the complexity added by arr.sort() method. So in Kotlin for array of Int, It compiles to use java.util.DualPivotQuicksort see this which in turn has complexity of O(n^2). see this. Other than that, this is also a valid approach.
I know It can be solved by keeping multiple arrays or using collections (which is what I ended up submitting), I want to know what I missed in the following approach
fun migratoryBirds(arr: Array<Int>): Int {
var maxCount = 0
var maxType = 0
var count = 0
var type = 0
arr.sort()
println(arr.joinToString(" "))
for (value in arr){
if (type != value){
if (count > maxCount){
maxCount = count
maxType = type
}
// new count values
type = value
count = 1
} else {
count++
}
}
return maxType
}
This code passes every scenario except for Test case 2 which has 73966 items for array. On my local machine, that array of 73k+ elements was causing timeout but I did test for array up-to 20k+ randomly generated value 1..5 and every time it succeeded. But I couldn't manage to pass Test case 2 with this approach. So even though I ended up submitting an answer with collection stream approach, I would really like to know what could I be missing in above logic.
I am running array loop only once Complexity should be O(n), So that could not be reason for failing. I am pre-sorting array in ascending order, and I am checking for > not >=, therefore, If two types end up having same count, It will still return the lower of the two types. And this approach is working correctly even for array of 20k+ elements ( I am getting timeout for anything above 25k elements).
The reason it is failing is this line
arr.sort()
Sorting an array takes O(n logn) time. However using something like a hash map this can be solved in O(n) time.
Here is a quick python solution I made to give you the general idea
# Complete the migratoryBirds function below.
def migratoryBirds(arr):
ans = -1
count = -1
dic = {}
for x in arr:
if x in dic:
dic[x] += 1
else:
dic[x] = 1
if dic[x] > count or dic[x] == count and x < ans:
ans = x
count = dic[x]
return ans
So i've tried interpreting this pseudocode a friend made and i wasn't exactly sure that my method returns the right result. Anyone who's able to help me out?
I've done some test cases where e.g. an array of [2,0,7] or [0,1,4] or [0, 8, 0] would return true, but not cases like: [1,7,7] or [2,6,0].
Array(list, d)
for j = 0 to d−1 do
for i = 0 to d−1 do
for k = 0 to d−1 do
if list[j] + list[ i] + list[k] = 0 then
return true
end if
end for
end for
end for
return false
And i've made this in java:
public class One{
public static boolean method1(ArrayList<String> A, int a){
for(int i = 0; i < a-1; i++){
for(int j = 0; j < a-1; j++){
for(int k = 0; k < a-1; k++){
if(Integer.parseInt(A.get(i)+A.get(j)+A.get(k)) == 0){
return true;
}
}
}
}
return false;
}
}
Thanks in advance
For a fix to your concrete problem, see my comment. A nicer way to write that code would be to actually use a list of Integer instead of String, because you will then want to convert the strings back to integers. So, your method looks better like this:
public static boolean method(List<Integer> A) {
for (Integer i : A)
for (Integer j : A)
for (Integer k : A)
if (i + j + k == 0)
return true;
return false;
}
See that you don't even need the size as parameter, since any List in Java embeds its own size.
Somehow offtopic
You're probably trying to solve the following problem: "Find if a list of integers contains 3 different ones that sum up to 0". The solution to this problem doesn't have to be O(n^3), like yours, it can be solved in O(n^2). See this post.
Ok, so here is what I believe the pseudo code is trying to do. It returns true if there is a zero in your list or if there are three numbers that add up to zero in your list. So it should return true for following test cases. (0,1,2,3,4,5), (1,2,3,4,-3). It will return false for (1,2,3,4,5). I just used d=5 as a random example. Your code is good for the most part - you just need to add the ith, jth and kth elements in the list to check if their sum equals zero for the true condition.
I am trying to encode conditional behavior for Verilog statements in a generate loop. For example, the code below returns an error.
module <something> (out);
parameter [4:0] someParam = 0;
output [5:0] out;
genvar l, m;
for(l=0; l<5; l=l+1) begin:STAGE_1
m = 0;
if(someParam[l] < 2)
m = l+2;
else begin
m = l-2;
end
if (m>16) assign out[l] = 1'b0;
else assign out[l] = 1'b1;
end
endmodule
The problem is that the variable m is not a constant and the code errors out. Is there any way I can use compile time variable inside a generate statement which would allow some functionality like the variable m above?
Thanks.
I didnt understand what you intended to calculate due to some errors in your code.
In general, for you to use a parameter in a statement you can use an always block with a if statement as following:
module <something> (out);
parameter [4:0] someParam = 0;
output out; // in this case out is only one bit. it can be more of course.
integer l,m; // no need for genver when not using generate
always (*) begin
m = 0;
for (l=0; l<5; l=l+1) begin:STAGE_1
if (someParam[l] == 1'b1) // nothing good comes for checking if a bit is less then 2
m = m+1; // just counting bits in someParam. doing +-2 does not make sense.
end
if (m >= 3)
out = 1'b1;
else
out = 1'b0;
end
The above is a majority function.
Good luck
Knowing that every recursive function can be translated to an iterative version. Can someone help me find the iterative version to this pseudo code? I am trying to optimize the code and recursion is clearly not the way to go
sub calc (a, b )
{
total = 0;
if(b <= 1)
return 1
if( 2*a > CONST)
for i IN (1..CONST)
total += calc(i, b-1) ;
else
for j IN (2*a..CONST)
total += calc(j, b-1) ;
return total;
}
CONST = 100;
print calc (CONST,2000);
Thanks for the help!
A refactoring from recursion to iteration is not the answer to your performance woes here. This algorithm benefits most from caching, in much the same way as the Fibonacci sequence does.
After writing a short test program in F#, with some sample data (CONST = 5, a = 0..10, b = 2..10):
The original program took 6.931 seconds
The cached version took 0.049 seconds
The solution is to keep a dictionary with a key of tuple(a,b) and look up the values before calculating. here is the algorithm with caching:
dictionary = new Dictionary<tuple(int, int), int>();
sub calc (a, b )
{
if (dictionary.Contains(tuple(a,b)))
return dictionary[tuple(a,b)];
else
{
total = 0;
if(b <= 1)
return 1
if( 2*a > CONST)
for i IN (1..CONST)
total += calc(i, b-1);
else
for j IN (2*a..CONST)
total += calc(j, b-1);
dictionary[tuple(a,b)] = total;
return total;
}
}
Edit: just to confirm that it was not the iterative nature of my testing that caused the performance gain, I tried them both again a with a single set of parameters (CONST = 5, a = 6, b = 20).
The cached version took 0.034 seconds
The original version is still running... (2+ minutes)
Only tail recursive algorithms can be converted to iterative algorithms. Your provided code is most definitely not tail recursive and thus it can't be easily convert to iterative form.
The solution to your performance problems is Memoization
The Following is the basic skeleton for my MATLAB program. Each box is a class definition.
Scroll down for the error.
Note: 1. Each Class has a custom constructor
The Error
Undefined function or variable 'Troom'.
Error in ==> wall>wall.wall at 31
function o = wall(Tr)
Error in ==> mainfile at 5
w1 = wall();
This comes when I create an object of Class wall from another file "mainfile"
Question
Why is this happening?
Am I getting wrong in the concepts of OOP for Matlab specific?
How do I resolve this?
Thanks in Advance!
PS: Code
function o = wall()
Tr = o.Troom*2;
o.N = round(1/o.dx) + 1;
o.T = Tr * ones(o.N,1);
o.Tinf = Tr;
o.update_properties();
end
Code 2
classdef wall
properties
dx = 0.01;
dt = 0.4;
L = 0.16;
N;
tlimit = 1505.2;
sbc = 5.670400e-8 % The Stefan-Boltzmann Constant
a;
hi; % Surface Conductivity of Inner Surface
bi;
ho; % Surface Conductivity of Outer Surface
bo;
lamb;
Troom = 298; % Room Temperature (K)
Tinf;
T;
room = compartment();
conc = concrete();
fire = fireProperties(Troom);
end
room = compartment();
conc = concrete();
fire = fireProperties(Troom);
Yeah, there's your problem right there. Troom can't be used in the context of the properties block. Either put the constant in for Troom or move these into the constructor where they belong.