I need any help for Matlab's thinking method.Ithink I can explaine my problem with a simple example better. Let's say that I have a characteristic function x=y+x0, x0's are may starting values.Then I want to define my function in a grid.Then I define a finer grid and I want to ask him if he knows where an arbitrary (x*,y*) is.To determine it mathematically I should ask where the corresponding starting point (x0*) is. If this startig point stay between x(i,1)
clear
%%%%%%%%%%&First grid%%%%%%%%%%%%%%%%%%%%
x0=linspace(0,10,6);
y=linspace(0,5,6);
for i=1:length(x0)
for j=1:length(y)
x(i,j)=y(j)+x0(i);
%%%%%%%%%%%%%%%%%%%Second grid%%%%%%%%%%%%%%%%%%
x0fine=linspace(0,10,10);
yfine=linspace(0,5,10);
for p=1:length(x0fine)
for r=1:length(yfine)
xfine(p,r)=yfine(r)+x0fine(p);
if (x(i,1)<xfine(p,1)')&(x0fine(p,1)'<x(i+1,1))%%%%I probabliy have my first mistake %here
% if y(j)<yfine(r)<y(j+1)
% xint(i,j)=(x(i,j)+x(i,j+1)+x(i+1,j)+x(i+1,j+1))./4;
% else
% xint(i,j)= x(i,j);
%end
end
end
end
end
While a < b < c is legal MATLAB syntax, I doubt that it does what you think it does. It does not check that a < b and b < c. What it does is, it checks whether a < b, returning a logical value (maybe an array of logicals) and then, interpreting this logical as 0 or 1, compares it against c:
>> 2 < 0 < 2
ans =
1
>> 2 < 0 < 1
ans =
1
>> 0 < 0 < 1
ans =
1
First in matlab you should avoid as much as possible to do loops.
For instance you can compute x and xfine, with the following code:
x0=linspace(0,10,6);
y=linspace(0,5,6);
x=bsxfun(#plus,x0',y);
x0fine=linspace(0,10,10);
yfine=linspace(0,5,10);
xfine=bsxfun(#plus,x0fine',yfine);
Then given (X*,y*) your want to fine x0*, in your simple example, you can just do: x0*=x*-y*, I think.
Related
This is really similar to Fibonacci Sequence problem. I understand the DP optimization with Fibonacci function using the for loop, but I'm having hard time to connect to this problem.
The recursion function I want to optimize is:
def cal(n):
if n <= 0:
return 1
else:
return cal(n-25)+cal(n-26)
Something like this may help:
(It's inspired by previous post)
from functools import cache
#cache
def cal(n):
if n <= 0:
return 1
else:
return cal(n-25) + cal(n-26)
print(cal(100))
The idea of a "for loop optimization" is that we calculate cal(0), cal(1), cal(2), ... consecutively. And when we want cal(n), we already have cal(n-25) and cal(n-26) stored in an array.
So, the following solution has linear complexity for non-negative n:
def cal(n):
mem = [1] # cal(0) is 1
for i in range(1, n + 1):
num = 1 if i - 25 < 0 else mem[i - 25]
num += 1 if i - 26 < 0 else mem[i - 26]
mem.append (num)
return mem[-1]
One can further optimize to make all the values cal(1), cal(2), ..., cal(n) globally available after calculating the last of them.
I've written out a potential solution to a Leetcode problem but I get this error involving maximum recursion depth. I'm really unsure what I'm doing wrong. Here's what I've tried writing:
def orangesRotting(grid):
R,C = len(grid), len(grid[0])
seen = set()
min_time = 0
def fresh_search(r,c, time):
if ((r,c,time) in seen or r < 0 or c < 0 or r >= R or c >= C or grid[r][c] == 0):
return
elif grid[r][c] == 2:
seen.add((r,c,0))
elif grid[r][c] == 1:
seen.add((r,c, time + 1))
fresh_search(r+1,c,time+1)
fresh_search(r-1,c,time+1)
fresh_search(r,c+1,time+1)
fresh_search(r,c-1,time+1)
for i in range(R):
for j in range(C):
if grid[i][j] == 2:
fresh_search(i,j,0)
for _,_,t in list(seen):
min_time = max(min_time,t)
return min_time
Even on a simple input like grid = [[2,1,1], [1,1,0], [0,1,1]]. The offending line always appears to be at the if statement
if ((r,c,time) in seen or r < 0 or c < 0 or r >= R or c >= C or grid[r][c] == 0):
Please note, I'm not looking for help in solving the problem, just understanding why I'm running into this massive recursion issue. For reference, here is the link to the problem. Any help would be appreciated.
So let's trace through what you are doing here. You iterate through the entire grid and if the value for that cell is 2 you call fresh_search for that cell. We'll start with [0,0]
In fresh_search you then add the cell with times seen = 0 to your set.
Now for all neighboring cells you call fresh_search so we'll just look at r+1. For r+1 your method fresh_search adds the cell to your set with times seen = 1 and then calls fresh_search again with all neighboring cells.
Next we'll just look at r-1 which is our origin and now fresh_search is being called with this cell and times seen = 2. Now this value isn't in the set yet because (0,0,0) != (0,0,2) so it adds it to the set and again calls fresh_search with the r+1 cell but now times seen = 3
and so on and so forth until max recursion.
I have an array 'A'. I want to do a loop over all the elements of A, checking to see if any are greater than or equal to 1. If they are, I would like to assign a '1' to a new array 'B' in the same element index of A.
How would I go about implementing this?
I have the cumbersome idea of:
for i in 1:end
for j in 1:end
if A[i,j] >= 1
B[i,j] = 1
else
B[i,j] = 0
end
end
end
but I would prefer something more succinct.
Just use broadcast:
B = A .≥ 1
You can certainly use broadcasting as Oscar suggested (e.g. B = A .>= 1), but there's also nothing wrong with loops, since loops are fast and avoid excess allocations. You really only need one loop though, and the if statement is slightly superfluous, so:
B = similar(A, Int64) # If B doesn't already exist, otherwise omit this line
#inbounds for i in eachindex(A)
B[i] = A[i] >= 1
end
The #inbounds is optional, but improves speed.
I am a newbie to programming .here I have been solving a simple problem in functional programming (OZ) which is finding the sum of the Digits of a 6 digit positive integer.
Example:- if n = 123456 then
output = 1+2+3+4+5+6 which is 21.
here I found a solution like below
fun {SumDigits6 N}
{SumDigits (N Div 1000) + SumDigits (N mod 1000)}
end
and it says the argument (N Div 1000) gives first 3 digits and the argument (N mod 1000) gives us last 3 digits. and yes I getting the correct solution but my Doubt is how could they giving correct solutions. I mean in given example isn't (N Div 1000) of 123456 gives 123 right not 1+2+3 and similarly (N mod 1000) of123456 gives us 456 not 4+5+6 right ?. in that case, the answer should be 123+456 which is equals to 579 not 21 right ? what Iam missing here.I apologize for asking such simple question but any help would be appreciated.
Thank you :)
You are missing the most important thing here.
It is supposed to happen in a loop and each time the value of N changes.
For example
in the first iteration
the Div gives 1 and mod gives 6 so you add 1 and 6 and store the result and the number is also modified (it becomes 2345)
in the second iteration
the div gives 2 and mod gives 5 you add 2+5+previous result and the number is also modified..
This goes on till the number becomes zero
Your function is recursive, so every time the number get smaller, untill is just 0, then it goes back summing all the partial result. You can do it with an accumulator to store the result, in this simple way:
declare
fun {SumDigit N Accumulator}
if N==0 then Accumulator
else {SumDigit (N div 10) Accumulator+(N mod 10)}
end
end
{Browse {SumDigit 123456 0}}
i think the most elegant way is the function --
static int SumOfDigit(int n)
{
if (n < 10) return n;
return SumOfDigit(SumOfDigit(n/10)+n%10);
}
simple and true :-)
int main()
{
int n,m,d,s=0;
scanf("%d",&n);
m=n;
while(m!=0)
{
d=m%10;
s=s+d;
m=m/10;
}
printf("Sum of digits of %d is %d",n,s);
}
Is there a way to make certain functions such as isinteger() work with JuMPArrays?
I am using Julia/JuMP to solve an optimization problem, and after I get the solution, I want to check if the solution is integer. So here is what I wrote:
#defVar(m, 0<= x[1:3] <= 1)
...
xstar = getValue(x)
if isinteger(xstar)
...
end
And I get an error saying isinteger() has no method matching isinteger(::JuMPArray).
Thanks
So in general you can get an underlying array from a JuMPArray by using [:], e.g.
m = Model()
#variable(m, 0 <= x[1:3] <= 1)
#variable(m, 0 <= y[1:10, 1:10] <= 1)
solve(m)
xstar = getvalue(x)[:]
ystar = getvalue(y)[:,:]
Note that the reason for this is that JuMPArrays don't have to start with index 1, so the user needs to explicitly say they want a normal Julia array before doing things.
Regardless, you shouldn't use isinteger. Solvers don't always return very precise answers, e.g. they might say x[1] = 0.999996 but they really mean it is 1. You should do something like
for i in 1:3
if getvalue(x[i]) >= 0.999
println("x[$i] is 1!")
elseif getvalue(x[i]) <= 0.001
println("x[$i] is 0!")
end
end
to make sure you don't get any false negatives. If the variable is restricted to be integer or binary, use iround, e.g.
for i in 1:3
v = iround(getvalue(x[i]))
if v == 1
println("x[$i] is 1!")
elseif v == 0
println("x[$i] is 0!")
end
end
but it looks like in this case you are just seeing if the solution is naturally 0 or 1.