Tag Info

New answers tagged

3

(myMatrix[[#, #]] = 1) & /@ myIndices;


5

f = MapAt[1&, #, Thread[{#2, #2}]] &; f[myMatrix, myIndices] (* {{1, 0, 0}, {0, 0, 0}, {0, 0, 1}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}} *)


3

myMatrixFinal = ReplacePart[myMatrix, {#, #} & /@ myIndices -> 1]


8

Try this: Set[myMatrix[[#, #]], 1] & /@ myIndices; Or: ReplacePart[myMatrix, {{#, #} & /@ myIndices -> 1}] Or: SparseArray[({#, #} -> 1 & /@ myIndices), Dimensions@myMatrix] // Normal


4

The documentation states: If no explicit Shortest or Longest is given, ordinary expression patterns are normally effectively assumed to be Shortest[p], while string patterns are assumed to be Longest[p]. Leftmost elements in a sequence of patterns have first priority, and explicit uses of Shortest have priority over this implicit shortest behavior. ...


2

FirstPosition allows for a default value: sizeFunc[a | b | d | e | f] = {1, 1}; sizeFunc[c] = {2, 3}; list = {a, b, c, d, e, f}; FirstPosition[list, _?(sizeFunc[#] != {1, 1} &), {Length @ list}] {3} sizeFunc[c] = {1, 1}; FirstPosition[list, _?(sizeFunc[#] != {1, 1} &), {Length @ list}] {6} Without FirstPosition one might use: ...


2

I'll define a sizeFunc to play with: Clear[sizeFunc] sizeFunc[a] = {1, 1}; sizeFunc[b] = {1, 1}; sizeFunc[c] = {3, 2}; sizeFunc[d] = {2, 4}; sizeFunc[e] = {1, 1}; sizeFunc[f] = {1, 1}; UPDATE: OP mentioned the desired behavior when all elements return {1, 1}. Taking that into consideration, one can define the following function: firstnonscalar[l_List] ...


2

If your size function behaves something like this: sizeFunc[x_] := {1, 1} sizeFunc[d] := {3, 2, 1} then Select can get you the first element matching your negative criterion. Like this: Select[{a, b, c, d, e, f}, sizeFunc[#]!={1, 1} &, 1] If you want to use Position to get the position of the element in the list (rather than the element itself), ...


-1

This should work: Replace[{484/45, -16 EulerGamma/3, -8 Log[2], PolyGamma[0, 1/Sqrt[2]], (48/5 + 2 I/5) Sqrt[2] Log[1 + Sqrt[2]]}, _?ExactNumberQ -> 1, 2] (* {1, EulerGamma, Log[2], PolyGamma[1, 1/Sqrt[2]], Sqrt[2] Log[1 + Sqrt[2]]}*)


3

To answer the question as asked, we modify the code as follows: replacementRule = Plus[ Dot[FRONT__, AA__, BACK__] , Dot[FRONT__, BB__, BACK__] ] :> Dot[FRONT, Plus[Dot[AA], Dot[BB]], BACK]}] w.a.b.r + w.c.d.r /. replacementRule First, we have changed -> (Rule) to :> (RuleDelayed) so that when the expression is re-written, it will write it ...


4

It can be done with w.a.b.r + w.c.d.r /. Dot[FRONT_, AA__, BACK_] + Dot[FRONT_, BB__, BACK_] :> Dot[FRONT, Dot[AA] + Dot[BB], BACK] w.(a.b + c.d).r However, I like function argument destructuring, so I would probably write f[Dot[w_, a__, r_] + Dot[w_, b__, r_]] := w.(Dot[a] + Dot[b]).r f[w.a.b.r + w.c.d.r] w.(a.b + c.d).r


3

An approach using ReplaceRepeated and a temporary tag. data = {"DD1", "B12", "CCC", "3AD", "C2A", "3D1", "1A1", "C11", "BBA", "322", "1D2", "B3C", "1BD", "CC1", "AC"}; list //. {bef___, PatternSequence[x_, m_] /; Head[m] =!= tag && StringFreeQ[m, DigitCharacter], aft___} :> {bef, tag[x, m], aft} /. tag -> List ...


7

Here is one way: lines={"123","312","anb","452","Xys"} ReleaseHold[ lines //. {bef___, PatternSequence[x_String, m_String?(StringFreeQ[#, DigitCharacter] &)], aft___} :> {bef, {Hold[x], m}, aft}] (* ==> {"123", {"312", "anb"}, {"452", "Xys"}} *) I changed the pattern so that it tests the Head of x and m as well, and wrap x in ...


2

One option is to apply the rule over and over again until it doesn't have any effect: list = {"DD1", "B12", "CCC", "3AD", "C2A", "3D1", "1A1", "C11", "BBA", "322", "1D2", "B3C", "1BD", "CC1", "AC"}; FixedPoint[Replace[#, { bef___, PatternSequence[x_, m_] /; StringFreeQ[m, DigitCharacter], aft___ } :> {bef, {x, m}, aft}] &, ...


2

Okay, I think here's a way you can do virtually everything you want. First, my original answer, which I had then moved to a comment to Mr.Wizard's answer. You can substitute in Unique: StringMatchQ[#, StringExpression @@ With[{each = p__ /; endsWithSpaceQ@p}, Table[each /. p -> Unique[], {2}]] ~~ "17"] & /@ {str1, str2} (* {True, True} *) ...


4

I don't know of any direct solution to this problem. I have always had to work around it, but usually I find that isn't too hard. In this case, as I imagine you know, you could just write: StringMatchQ[#, Repeated[__ ~~ " ", {2}] ~~ "17"] & /@ {str1, str2} {True, True} Further this is far more efficient as it is run in an optimized string ...


5

If it's absolutely necessary to use the symbols as you've defined them, here's one option. (I've added FRH to the list to show that it doesn't get matched.) Cases[{RBI, RCD, ASD, FGH, FRH}, a_ /; StringMatchQ[ToString @ a, "R" ~~ ___]] results in {RBI, RCD} which is a list of Symbols (not a list of Strings). Now, there's a problem if you have already ...


3

I would use Cases with a condition and SymbolName. Cases[step[2], (symbol_ -> _) /; StringMatchQ[SymbolName[symbol], "k*p"]] Another solution: step[2] /. (symbol_ -> value_) /; Not@StringMatchQ[SymbolName[symbol], "k*p"] :> Nothing This solution makes use of Nothing which is new in Mathematica version 10.2. Nothing could be replaced by ...


2

If you want to use a pattern, you could use Cases[step[2], Alternatives@@HoldPattern/@Thread[ToExpression[Names["Global`k*p"]]->_Real]] (* {k1p -> 1.5396, k2p -> 1.91751} *) Technically this does not convert anything to strings, it just looks up all the user-defined names that match "k*p". It's not really elegant though. Alternatively you can ...


4

I don't think you can avoid using strings, but that doesn't mean the output will contain strings. Pick[step[2], StringMatchQ[ToString /@ step[2][[All, 1]], "k*p"]] {k1p -> 1.09503, k2p -> 1.32185}


3

The second one does not work as intended because EvenQ[x] always returns False if x is not "manifestly an even integer" (quote from docs.) Since you use -> instead of :>, the expression If[EvenQ[s], w[s], 0] is evaluated at once, and since s is a symbol at that stage, it is not manifestly an even integer. The first example works because s == 2 is ...


3

I am answering the question in an interesting, thorough way for the reader based on the useful comments I had from other community members. I believe this example is excellent for demonstrating many pattern oriented features inside function definitions. Let me know what you think. Predicate Definition listEmptyQ[lst_List] := Length[lst] == 0 Testing List ...


3

You can use repeated replacement, this will only keep elements that are strictly increasing. list = {1,2,3,4,6,5,7,8}; list = list//. {a___, x_, y_, b___} /; y < x :> {a, x, b} Which gives: {1, 2, 3, 4, 6, 7, 8} In the case that the all elements in Rest@list are less than the first element, a decreasing list for instance, it will return only ...


1

a = {1, 2, 5, 6, 8, 5, 4, 9, 12, 11}; Union@(Max /@ Table[Take[a, i], {i, Length[a]}]) (* {1, 2, 5, 6, 8, 9, 12} *)


8

The answer to the question depends upon what exactly should be called as "graphics primitive". In this answer from the practical point of view I define it as a container which can be found inside of Graphics or Graphics3D, which draws something and is not a graphical directive or Dynamic wrapper. This definition differs from the usual meaning but covers all ...


7

Since there seems no other simple answer at this time I propose the approach of rendering a Graphics expression and seeing if it has errors. By definition this will pass both primitives and directives, as well as inert expressions such as {}. I hope it nevertheless serves some purpose. I rasterize the graphic and look for the tell-tale pink warning color. ...


8

This bug has been fixed in version 10.2. $Version (* "10.2.0 for Linux x86 (64-bit) (July 6, 2015)" *) matchLists[patt_] := MatchQ[#, patt] & /@ {{}, {1}, {1, 2}, {1, 2, 3}, {1, 2, 3, 4}} matchLists[{_ | PatternSequence[]}] matchLists[{x_ | PatternSequence[]}] (* {True, True, False, False, False} *) (* {True, True, False, False, False} *) ...


1

Usually one does not need what you ask for. E.g. a pattern for an even integer greater than 10: x_Integer?EvenQ /; x > 10 (_Integer is not strictly necessary here as only integers will pass EvenQ however it should make the pattern a bit more efficient.) But since it is an interesting quesiton here is one idea: matchAll[expr_, form_] := ...


5

To directly get the opposite of Alternatives, you could negate each pattern with Except and then negate the Alternatives: also[patts__] := Except[Alternatives @@ Except /@ {patts}] Cases[Range[1, 15, 1/2], _Integer ~also~ _?(# > 10 &)] (* {11, 12, 13, 14, 15} *) Generally some other approach will be simpler, though, as discussed in the comments.


17

Edit: It was pointed out that the original form is not bullet-proof, e.g. GraphicsPrimitiveQ /@ {InputNotebook, Unique, Sequence} all returned True. However, when looking upon this answer about generating new graphics primitives, a superior answer came to light: Clear[GraphicsPrimitiveQ]; GraphicsPrimitiveQ[s_Symbol | (s_)[___]] := 0 < ...


7

If you are only ever going to call it as f[a^b] (that is, f[Power[a,b]]), you want to look at the attribute HoldFirst (or HoldAll or similar). Specifically: SetAttributes[f, HoldFirst]; f[a_^2] := a Alternatively, SetAttributes[f, HoldFirst]; f[x_] := Unevaluated[x] /. {a_^2 :> a} I'm always wary of using Unevaluated, though. Edited to add: ...


4

One way to do this: Attributes[f] = {HoldAll}; f[x_] := ReleaseHold[Hold[x] /. {Power[a_, b_] :> a}]; Then: f[3^2] gives 3. And: f[10000000000000000000000000000000000000000000^1000000000000000] gives 10000000000000000000000000000000000000000000 And: f[10^10^10] gives 10 And: f[(10^10)^10] gives 10000000000 (10^10).


2

I frequently write functions that take one or more arguments which I limit to those quantities that mathematicians call real numbers. In Mathematica that means any quantity satisfying NumericQ excepting complex numbers. To facilitate writing such functions, I define a pattern validNum = Except[_Complex, _?NumericQ]; This pattern is used like so: f[x : ...


10

To match your literal request you need Alternatives rather than Or. Either x : (_Integer | _Real) or x_Integer | x_Real will work. Following what Szabolcs and "Guess who it is" wrote you might define a realQ like so: realQ = NumericQ[#] && Im[#] == 0 &; f[x_?realQ] := x^2 f /@ {1, Pi, 1.3, 2/3, x^2, 7.1 - 2.8 I} {1, π^2, 1.69, 4/9, f[x^2], ...


4

This question might end up closed as it is hard to know what was in the minds of the language designers in every case. However I think a reasonable answer can be given here so I shall try. The high-level Mathematica language is arguably built on pattern matching. It it therefore natural that many functions also use, operate on, or work with patterns. For ...


3

If your pattern is not very big, you could use "brute force". Replace a sub-pattern with more general sub-pattern and check whether pattern matches expression. Repeat it with some subset of possible sub-patterns. This task can be automated using following function. It returns list of pairs. First element of pair is rule replacing position of sub-pattern ...


2

The best solution is to use RegionQ, a simple solution suggested by ilian. RegionQ is a function that takes a region as an argument and returns whether it is a valid region. Here is how I used it: regCells = Select[MeshPrimitives[DiscretizedRegion, 3], RegionQ]; This only keeps the regions returned by MeshPrimitives which are valid regions, which allows ...


0

Once you select the nearest element for list2[[1]] then other elements from list2 are practically directly assigned. There is one element from list2 not well assigned and it is -1067.4. Its partner -1115.6 is further than -1054.7. When you first reverse the order of initial lists, the desired solution is obtained. This minimize the Total value of ...


3

I'm not sure I correctly interpreted what you really are looking for, because you mention MapThread that works on elements on the same position in the two lists, whereas in the description you say that for each element of list2 you want the closest from list1. Moreover, this means that once you selected an element from list1, it cannot be considered for ...



Top 50 recent answers are included