Mathematica Do/For loop with "Delete" or "Drop" does not work - wolfram-mathematica

initlNum453 = List[];
num1 = 2;
(*Pt1, initial work to make initlNum full of good variables*)
algorithmicNum = 1;
For[i7 = 1, i7 <= (num1 + 1)^2, i7++,
AppendTo[initlNum453, algorithmicNum];
If[((algorithmicNum) == (num1 + 1)), algorithmicNum = 1,
algorithmicNum++];
];
(*Pt2, delete unneeded variables*)
deleteValue = 1;
Do[
Delete[initlNum453, deleteValue];
deleteValue = (deleteValue + num1 + 2);
, {num1 + 1}
]
Here's a snippet of the code I'm trying to make (it involves pseudo-automating Lagrange polynomials). It should be simple; the first part creates a series of numbers in a list, and then the second should be delete a particular section (e.g., the 1,4,7 if n=2).
For some reason, one of the following occurs:
No Error, but the elements in the list remains the same/no elements get deleted
Taking out the semicolon says that the "Tag Times in ___ is Protected"-- can someone explain what exactly this means?
When putting this into a Module, the error states that the expression .' cannot be used as a part specification. Use Key[.`] instead.
In any case, I don't understand why something as simple as this is just doesn't work on Mathematica. The "Delete" function works outside of a for/do loop, but doesn't inside-- can someone explain why or tell me what I did wrong?
Thanks for your help! I appreciate it!

You need to write something like
initlNum453 = Delete[initlNum453, deleteValue]

Related

Julia: define method for custom type

I apologize if this has been answered before, I didn't find a straight answer for this among my search results.
I'm going through "Learn Julia The Hardway" and I can't really find where's the difference in my code vs the example in the book. Whenever I run it I get the following error:
TypeError: in Type{...} expression, expected UnionAll, got a value of type typeof(+)
Here's the code:
struct LSD
pounds::Int
shillings::Int
pence::Int
function LSD(l,s,d)
if l<0 || s<0 || d<0
error("No negative numbers please, we're british")
end
if d>12 error("That's too many pence") end
if s>20 error("That's too many shillings") end
new(l,s,d)
end
end
import Base.+
function +{LSD}(a::LSD, b::LSD)
pence_s = a.pence + b.pence
shillings_s = a.shillings + b.shillings
pounds_s = a.pounds + b.pounds
pences_subtotal = pence_s + shillings_s*12 + pounds_s*240
(pounds, balance) = divrem(pences_subtotal,240)
(shillings, pence) = divrem(balance,12)
LSD(pounds, shillings, pence)
end
Another quick question, I haven't got yet to the functions chapter, but it catches my attention that there is no "return" at the end of the functions, I'm guessing that if it isn't stated a function will return the last evaluated value, am I right?
This appears to be using very old Julia syntax (I think from version 0.6). I think you just want function +(a::LSD, b::LSD)

Lua 'attempt to call a number value near for..in' error due to unrelated table index assignment -- why?

I'm writing some Lua scripts in Tabletop Simulator and seeing the error attempt to call a number value near for..in that has me completely perplexed. Here's the code snippet with the for loop that is causing the error:
function resetTurnOrder()
local map = getObjectFromGUID(GUIDs.Map)
local shift, center, points = map.getPosition(), map.getTable('MapData').center, map.getSnapPoints()
local i, p = 0
for nation, guids in pairs(GUIDs.Nations) do
print('Resetting turn order for ' .. nation)
if checkScenario(nation) then
i = i + 1
p = map.positionToLocal(shift - points[i].position)
p[1] = p[1] * 0.75 + center[1] * 0.25
p[3] = p[3] * 0.75 + center[3] * 0.25
getObjectFromGUID(guids.turn_token).setPositionSmooth(map.positionToWorld(p), false, false)
getObjectFromGUID(guids.turn_token).setRotationSmooth({0, points[i].rotation[2], 0}, false, false)
print('Done resetting turn order for ' .. nation)
else
print(nation .. ' not in this scenario')
end
end
end
Okay, so first of all I will say that the error went away by commenting out the two lines that assign directly to p[1] and p[3], and when I replaced those lines with the equivalent statement
p = {p[1] * 0.75 + center[1] * 0.25, p[2], p[3] * 0.75 + center[3] * 0.25}
then everything worked perfectly. However, I am completely dumbfounded as to why this would fix the error. I use this exact for loop definition in like half a dozen places to iterate over the players and their components (which are stored in the global GUIDs) and it has worked flawlessly everywhere else.
To add a little more detail, even with the old code the first iteration of the loop works perfectly. The first turn token is moved to its proper position, both messages are printed, but the error prevents further iterations. The error is clearly occurring when incrementing the loop iterator, but I can't understand how assigning directly to p[1] and p[3] could possibly interfere with this but assigning to p is fine. One more detail: declaring p inside the for loop instead of outside beforehand didn't help.
(EDITED TO ADD MORE DETAILS)
After more testing it looks like #luther is probably correct that something weird is going on with the metatable for the value returned by positionToLocal. The value returned by this function is a Vector defined by Tabletop Simulator which I believe is an extension of Unity's Vector3 type. An important detail is that this type allows you to refer to the indices x,y,z and 1,2,3 interchangeably.
So, I replaced the p[1] and p[3] assignments with p.x and p.z which fixed the error. This seems to imply that the Vector returned by positionToLocal did not define indices 1,2,3 explicitly but instead uses a metamethod to link those indices to x,y,z. And, somehow, that metamethod is messing with the loop iterator... but honestly that still boggles my mind.
GUIDs.Nations is the table passed to the pairs() function which is used to generate the iterator and it is basically a constant--I never add to or update it in any function because it contains static GUIDs. It certainly has no connection to p.
FURTHER DETAILS
This definitely seems likely to be connected to Tabletop Simulator's Vector implementation: https://forums.tabletopsimulator.com/showthread.php?8344-For-loop
The above example just uses a simple numeric for loop to update indices 1,2,3 of a Vector value, and an assignment statement which uses i to index the Vector ends up changing the value of i to the same value that is assigned.
I'm still unable to understand how this is even possible in the language though...
Okay, I'm certain that this is a bug in Moonsharp, which is the Lua interpreter used by Tabletop Simulator: https://github.com/moonsharp-devs/moonsharp/issues/133
The bug was fixed in March 2016 (https://github.com/moonsharp-devs/moonsharp/commit/3ebc0e1fc706c452df9b309d51daec88a15eb0d1) but it seems like TTS probably hasn't updated Moonsharp.

Can someone explain how this ruby basic-calculator code handles addition and subtraction?

So I was working on a Codewars problem here, and found some code posted to Github that works out-of-the-box. Problem is, I don't understand how part of it works. Here are the Codewars directions:
Description:
Create a simple calculator that given a string of operators (+ - * and /) and numbers separated by spaces returns the value of that expression
Example:
Calculator.new.evaluate("2 / 2 + 3 * 4 - 6") # => 7
Remember about the order of operations! Multiplications and divisions have a higher priority and should be performed left-to-right. Additions and subtractions have a lower priority and should also be performed left-to-right.
Here's the code:
class Calculator
def evaluate(string)
operator_stack = []
number_stack = []
string.split(" ").each do |token|
if /\d/.match(token)
number_stack << token.to_i
elsif operator_stack.length > 0 && /[*]|[\/]/.match(operator_stack[-1])
x, y = number_stack.pop, number_stack.pop
temp_result = y.send(operator_stack.pop, x)
number_stack << temp_result
operator_stack << token
else
operator_stack << token
end
end
while(number_stack.length > 0 && operator_stack.length > 0)
x, y = number_stack.shift, number_stack.shift
temp_result = x.send(operator_stack.shift,y)
number_stack.unshift(temp_result)
end
return number_stack[0]
end
end
Now I've learned enough Ruby that I can read through and understand what the various functions do, but when it comes to the mathematical operations the code does, I don't see where or how it handles addition and subtraction. There is some regex that's used to match for multiplication and division present in this line:
elsif operator_stack.length > 0 && /[*]|[\/]/.match(operator_stack[-1])
But since I don't see the plus or minus sign anywhere in the code, I don't get how it performs those operations. Can anyone help?
BTW, I'm done with the Codewars problem and have moved on. I also discovered you can solve this calculator problem with "instance_eval string", which blew my mind when I first saw it. But, it makes sense after reading through what I found here. I should have guessed that there was a one-liner that would work as a basic calculator :)
I would still like to know how this code handles addition and subtraction. Can anyone enlighten me?
The actual operations are performed in these lines:
temp_result = y.send(operator_stack.pop, x)
and later
temp_result = x.send(operator_stack.shift,y)
which says "send the operator_stack.shift/pop message with parameter y to objectx, which is basically the same as doing x <operator> y where <operator> is the operator on top of operator_stack

Employ early bail-out in MATLAB

There is a example for Employ early bail-out in this book (http://www.amazon.com/Accelerating-MATLAB-Performance-speed-programs/dp/1482211297) (#YairAltman). for speed improvement we can convert this code:
data = [];
newData = [];
outerIdx = 1;
while outerIdx <= 20
outerIdx = outerIdx + 1;
for innerIdx = -100 : 100
if innerIdx == 0
continue % skips to next innerIdx (=1)
elseif outerIdx > 15
break % skips to next outerIdx
else
data(end+1) = outerIdx/innerIdx;
newData(end+1) = process(data);
end
end % for innerIdx
end % while outerIdx
to this code:
function bailableProcessing()
for outerIdx = 1 : 5
middleIdx = 10
while middleIdx <= 20
middleIdx = middleIdx + 1;
for innerIdx = -100 : 100
data = outerIdx/innerIdx + middleIdx;
if data == SOME_VALUE
return
else
process(data);
end
end % for innerIdx
end % while middleIdx
end % for outerIdx
end % bailableProcessing()
How we did this conversion? Why we have different middleIdx range in new code? Where is checking for innerIdx and outerIdx in new code? what is this new data = outerIdx/innerIdx + middleIdx calculation?
we have only this information for second code :
We could place the code segment that should be bailed-out within a
dedicated function and return from the function when the bail-out
condition occurs.
I am sorry that I did not clarify within the text that the second code segment is not a direct replacement of the first. If you reread the early bail-out section (3.1.3) perhaps you can see that it has two main parts:
The first part of the section (which includes the top code segment) illustrates the basic mechanism of using break/continue in order to bail-out from a complex processing loop, in order to save processing time in computing values that are not needed.
In contrast, the second part of the section deals with cases when we wish to break out of an ancestor loop that is not the direct parent loop. I mention in the text that there are three alternatives that we can use in this case, and the second code segment that you mentioned is one of them (the other alternatives are to use dedicated flags with break/continue and to use try/catch blocks). The three code segments that I provided in this second part of the section should all be equivalent to each other, but they are NOT equivalent to the code-segment at the top of the section.
Perhaps I should have clarified this in the text, or maybe I should have used the same example throughout. I will think about this for the second edition of the book (if and when it ever appears).
I have used a variant of these code segments in other sections of the book to illustrate various other aspects of performance speedups (for example, 3.1.4 & 3.1.6) - in all these cases the code segments are NOT equivalent to each other. They are merely used to illustrate the corresponding text.
I hope you like my book in general and think that it is useful. I would be grateful if you would place a positive feedback about it on Amazon (direct link).
p.s. - #SamRoberts was correct to surmise that mention of my name would act as a "bat-signal", attracting my attention :-)
it's all far more simple than you think!
How we did this conversion?
Irrationally. Those two codes are completely different.
Why we have different middleIdx range in new code?
Randomness. The point of the author is something different.
Where is checking for innerIdx and outerIdx in new code?
dont need that, as it's not intended to be the same code.
what is this new data = outerIdx/innerIdx + middleIdx calculation?
a random calculation as well as data(end+1) = outerIdx/innerIdx; in the original code.
i suppose the author wants to illustrate something far more profoundly: that if you wrap your code that does (possibly many) loops (fors/whiles, doesnt matter) inside a function and you issue a return statement if you somehow detect that you're done, it will result in an effectively "bailable" computation, e.g. the method that does the work returns earlier than it would normally do. that is illustrated here by the condition that checks on data == SOME_VALUE; you can have your favourite bailout condition there instead :-)
moreover, the keywords [continue/break] inside the first example are meant to illustrate that you can [skip the rest of/leave] the inner-most loop from whereever you call them. in principal, you can implement a bailout using these by e.g.
bailing = false;
for outer = 1:1000
for inner = 1:1000
if <somebailingcondition>
bailing = true;
break;
else
<do stuff>
end
end
if bailing
break;
end
end
but that would be very clumsy as that "cascade" of breaks will need to be as long as you have nested loops and messes up the code.
i hope that could clarify your issues.

Processing Language: for loop elaboration, please

I've just started learning the Processing programming language from the book "Getting Started with Processing". So far, it has been very intuitive to me until I reached the for loop.
size(480, 120);
smooth();
strokeWeight(8);
for (int i = 20; i < 400; i += 60) {
line(i, 40, i + 60, 80);
}
Sure, this example from the book works just fine in the PDE (Processing Development Environment) however, here's what doesn't make sense to me:
The first time through the for-loop, it reads the first parameter 'int i = 20' and maybe the second 'i < 400' however, it appears to ignore entirely the last parameter of 'i +=60'
Then after that first pass, the for-loop appears to totally ignore the first parameter of 'int i = 20' while reading the other two parameters.
Can someone please help me to understand what is really going on here?
To understand this, you need to know how for-loop works. See the flowchart:

Resources