Dot products and For-loopsWhy should I avoid the For loop in Mathematica?Maximizing functions with Which statementsHow do I produce iterative equations and bifurcation diagrams?How do I write nested for-loops?How would I write iterative code to try multiple coefficients for an equation?Plotting Invariant Manifolds of the Henon MapTrouble defining function for homeworkSymmetry of a Dot with functions with argumentsFor Loop and Sum
Has Boris Johnson ever referred to any of his opponents as "traitors"?
Does the US Armed Forces refuse to recruit anyone with an IQ less than 83?
Lighthouse Alternatives
Is "Ram married his daughter" ambiguous?
Should I be an author on another PhD student's paper if I went to their meetings and gave advice?
Booting Ubuntu from USB drive on MSI motherboard -- EVERYTHING fails
Digital Bananas
How to refresh wired service getRecord manually?
Sci-fi story about aliens with cells based on arsenic or nitrogen, poisoned by oxygen
How can I find places to store/land a private airplane?
Quote to show students don't have to fear making mistakes
Does it require less energy to reach the Sun from Pluto's orbit than from Earth's orbit?
How do we know Nemesis is not a black hole (or neutron star)?
What is the Japanese equivalent of 'you're in my heart'?
Generating numbers with cubes
Why is there such a singular place for bird watching?
Job interview by video at home and privacy concerns
As an interviewer, how to conduct interviews with candidates you already know will be rejected?
Canteen Cutlery Issue
Is morphing a creature effectively a cost?
What are one's options when facing religious discrimination at the airport?
Mac no longer boots
How to protect bash function from being overridden?
What powers or limits devil promotion?
Dot products and For-loops
Why should I avoid the For loop in Mathematica?Maximizing functions with Which statementsHow do I produce iterative equations and bifurcation diagrams?How do I write nested for-loops?How would I write iterative code to try multiple coefficients for an equation?Plotting Invariant Manifolds of the Henon MapTrouble defining function for homeworkSymmetry of a Dot with functions with argumentsFor Loop and Sum
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty
margin-bottom:0;
.everyonelovesstackoverflowposition:absolute;height:1px;width:1px;opacity:0;top:0;left:0;pointer-events:none;
$begingroup$
I'm taking a class where we're working with matrix applications inside of Mathematica. In this case, we're analyzing senatorial votes that have been numericized so that a value of 1 corresponds to "aye," -1 corresponds to "nay," and 0 corresponds to no vote/abstain.
Taking the dot products of these values, I'm trying to find, for each senator, the senator(s) with the most and least similar voting patterns (largest and smallest dot products) and plot these in a chart.
This may not be the most efficient code to accomplish this, but given that it's for a class, I am supposed to modify what's below:
closestvoter[n_] :=
Module[max = 0, k = 0, close = 0,
For[i = 1, i < 100, i++,
k = senatorvote[n] . senatorvote[i];
If[k >= max && i != n, close = i; max = k];
];
close
]
The way the code works right now, it will only give me a single value of i when sometimes there is more than one senator that produces the same dot product. How can I get the loop to check and print all values of i that satisfy this?
conditional homework iterators
$endgroup$
add a comment
|
$begingroup$
I'm taking a class where we're working with matrix applications inside of Mathematica. In this case, we're analyzing senatorial votes that have been numericized so that a value of 1 corresponds to "aye," -1 corresponds to "nay," and 0 corresponds to no vote/abstain.
Taking the dot products of these values, I'm trying to find, for each senator, the senator(s) with the most and least similar voting patterns (largest and smallest dot products) and plot these in a chart.
This may not be the most efficient code to accomplish this, but given that it's for a class, I am supposed to modify what's below:
closestvoter[n_] :=
Module[max = 0, k = 0, close = 0,
For[i = 1, i < 100, i++,
k = senatorvote[n] . senatorvote[i];
If[k >= max && i != n, close = i; max = k];
];
close
]
The way the code works right now, it will only give me a single value of i when sometimes there is more than one senator that produces the same dot product. How can I get the loop to check and print all values of i that satisfy this?
conditional homework iterators
$endgroup$
$begingroup$
Why should I avoid the For loop in Mathematica? mathematica.stackexchange.com/questions/134609/…
$endgroup$
– Roman
Apr 16 at 6:49
add a comment
|
$begingroup$
I'm taking a class where we're working with matrix applications inside of Mathematica. In this case, we're analyzing senatorial votes that have been numericized so that a value of 1 corresponds to "aye," -1 corresponds to "nay," and 0 corresponds to no vote/abstain.
Taking the dot products of these values, I'm trying to find, for each senator, the senator(s) with the most and least similar voting patterns (largest and smallest dot products) and plot these in a chart.
This may not be the most efficient code to accomplish this, but given that it's for a class, I am supposed to modify what's below:
closestvoter[n_] :=
Module[max = 0, k = 0, close = 0,
For[i = 1, i < 100, i++,
k = senatorvote[n] . senatorvote[i];
If[k >= max && i != n, close = i; max = k];
];
close
]
The way the code works right now, it will only give me a single value of i when sometimes there is more than one senator that produces the same dot product. How can I get the loop to check and print all values of i that satisfy this?
conditional homework iterators
$endgroup$
I'm taking a class where we're working with matrix applications inside of Mathematica. In this case, we're analyzing senatorial votes that have been numericized so that a value of 1 corresponds to "aye," -1 corresponds to "nay," and 0 corresponds to no vote/abstain.
Taking the dot products of these values, I'm trying to find, for each senator, the senator(s) with the most and least similar voting patterns (largest and smallest dot products) and plot these in a chart.
This may not be the most efficient code to accomplish this, but given that it's for a class, I am supposed to modify what's below:
closestvoter[n_] :=
Module[max = 0, k = 0, close = 0,
For[i = 1, i < 100, i++,
k = senatorvote[n] . senatorvote[i];
If[k >= max && i != n, close = i; max = k];
];
close
]
The way the code works right now, it will only give me a single value of i when sometimes there is more than one senator that produces the same dot product. How can I get the loop to check and print all values of i that satisfy this?
conditional homework iterators
conditional homework iterators
edited Apr 16 at 4:43
m_goldberg
91.8k8 gold badges75 silver badges210 bronze badges
91.8k8 gold badges75 silver badges210 bronze badges
asked Apr 16 at 3:25
H. S.H. S.
261 bronze badge
261 bronze badge
$begingroup$
Why should I avoid the For loop in Mathematica? mathematica.stackexchange.com/questions/134609/…
$endgroup$
– Roman
Apr 16 at 6:49
add a comment
|
$begingroup$
Why should I avoid the For loop in Mathematica? mathematica.stackexchange.com/questions/134609/…
$endgroup$
– Roman
Apr 16 at 6:49
$begingroup$
Why should I avoid the For loop in Mathematica? mathematica.stackexchange.com/questions/134609/…
$endgroup$
– Roman
Apr 16 at 6:49
$begingroup$
Why should I avoid the For loop in Mathematica? mathematica.stackexchange.com/questions/134609/…
$endgroup$
– Roman
Apr 16 at 6:49
add a comment
|
3 Answers
3
active
oldest
votes
$begingroup$
I recommend you make close
a list in which you can accumulate values of i
that give the same k
. The test for updating close
and max
will have to more elaborate.
Clear[closestvoter]
closestvoter[n_, maxn_] :=
Module[max = 0, k = 0, close = ,
For[i = 1, i <= maxn, i++,
If[i != n,
k = senatorvote[n].senatorvote[i];
Which[
k == max, AppendTo[close, i],
k > max, close = i; max = k]]];
max, close]]
Note this version of closestvoter
reports max
as well as the all the indexes for which k == max
.
Contrived test data.
SeedRandom[42]; Clear[senatorvote];
Do[senatorvote[i] = RandomInteger[-1, 1, 30], i, 25];
Here is the results for the contrived data.
Column @ Table[Join[i, closestvoter[i, 25]], i, 25]
We see that only the first senator has the same maximum score with more than one other senator.
$endgroup$
add a comment
|
$begingroup$
Define the votes as lists instead of a function:
SeedRandom[1234];
senatorvote = RandomInteger[-1, 1, 25, 30];
closestvoters[n_] := MaximalBy[Delete[Range[Length[senatorvote]], n],
senatorvote[[n]].senatorvote[[#]] &]
farthestvoters[n_] := MinimalBy[Range[Length[senatorvote]],
senatorvote[[n]].senatorvote[[#]] &]
test:
closestvoters[1]
13, 20
farthestvoters[1]
5
$endgroup$
add a comment
|
$begingroup$
In addition to Roman's post, here is a method to compute all closest and farthest voters to all senators at once as follows; this should be about to 2 orders of magnitude faster than Roman's code.
SeedRandom[1234];
senatorvote = RandomInteger[-1, 1, 2500, 3000];
A = senatorvote.senatorvote[Transpose];
closestvoters = Flatten[Position[#, Max[#]]] & /@ (A - 2 DiagonalMatrix[Diagonal[A]]);
farthestvoters = Flatten[Position[#, Min[#]]] & /@ A;
By computing A
first, you can take greatest advantage of the linear algebra capabilities of your hardware. Afterwards, you have to find only the minimum and maximum positions per row. So the closest voters to senator n
will be written into closestvoters[[n]]
.
Since Position
is somewhat slow in finding positions of integers in a vector (notice that Position
can do a lot more than that which comes at a cost), here a faster implementation utilizing an undocumented function:
closestvoters = Random`Private`PositionsOf[#, Max[#]] & /@ (A - 2 DiagonalMatrix[Diagonal[A]]);
farthestvoters = Random`Private`PositionsOf[#, Min[#]] & /@ A;
$endgroup$
add a comment
|
Your Answer
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "387"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmathematica.stackexchange.com%2fquestions%2f195264%2fdot-products-and-for-loops%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
I recommend you make close
a list in which you can accumulate values of i
that give the same k
. The test for updating close
and max
will have to more elaborate.
Clear[closestvoter]
closestvoter[n_, maxn_] :=
Module[max = 0, k = 0, close = ,
For[i = 1, i <= maxn, i++,
If[i != n,
k = senatorvote[n].senatorvote[i];
Which[
k == max, AppendTo[close, i],
k > max, close = i; max = k]]];
max, close]]
Note this version of closestvoter
reports max
as well as the all the indexes for which k == max
.
Contrived test data.
SeedRandom[42]; Clear[senatorvote];
Do[senatorvote[i] = RandomInteger[-1, 1, 30], i, 25];
Here is the results for the contrived data.
Column @ Table[Join[i, closestvoter[i, 25]], i, 25]
We see that only the first senator has the same maximum score with more than one other senator.
$endgroup$
add a comment
|
$begingroup$
I recommend you make close
a list in which you can accumulate values of i
that give the same k
. The test for updating close
and max
will have to more elaborate.
Clear[closestvoter]
closestvoter[n_, maxn_] :=
Module[max = 0, k = 0, close = ,
For[i = 1, i <= maxn, i++,
If[i != n,
k = senatorvote[n].senatorvote[i];
Which[
k == max, AppendTo[close, i],
k > max, close = i; max = k]]];
max, close]]
Note this version of closestvoter
reports max
as well as the all the indexes for which k == max
.
Contrived test data.
SeedRandom[42]; Clear[senatorvote];
Do[senatorvote[i] = RandomInteger[-1, 1, 30], i, 25];
Here is the results for the contrived data.
Column @ Table[Join[i, closestvoter[i, 25]], i, 25]
We see that only the first senator has the same maximum score with more than one other senator.
$endgroup$
add a comment
|
$begingroup$
I recommend you make close
a list in which you can accumulate values of i
that give the same k
. The test for updating close
and max
will have to more elaborate.
Clear[closestvoter]
closestvoter[n_, maxn_] :=
Module[max = 0, k = 0, close = ,
For[i = 1, i <= maxn, i++,
If[i != n,
k = senatorvote[n].senatorvote[i];
Which[
k == max, AppendTo[close, i],
k > max, close = i; max = k]]];
max, close]]
Note this version of closestvoter
reports max
as well as the all the indexes for which k == max
.
Contrived test data.
SeedRandom[42]; Clear[senatorvote];
Do[senatorvote[i] = RandomInteger[-1, 1, 30], i, 25];
Here is the results for the contrived data.
Column @ Table[Join[i, closestvoter[i, 25]], i, 25]
We see that only the first senator has the same maximum score with more than one other senator.
$endgroup$
I recommend you make close
a list in which you can accumulate values of i
that give the same k
. The test for updating close
and max
will have to more elaborate.
Clear[closestvoter]
closestvoter[n_, maxn_] :=
Module[max = 0, k = 0, close = ,
For[i = 1, i <= maxn, i++,
If[i != n,
k = senatorvote[n].senatorvote[i];
Which[
k == max, AppendTo[close, i],
k > max, close = i; max = k]]];
max, close]]
Note this version of closestvoter
reports max
as well as the all the indexes for which k == max
.
Contrived test data.
SeedRandom[42]; Clear[senatorvote];
Do[senatorvote[i] = RandomInteger[-1, 1, 30], i, 25];
Here is the results for the contrived data.
Column @ Table[Join[i, closestvoter[i, 25]], i, 25]
We see that only the first senator has the same maximum score with more than one other senator.
edited Apr 16 at 4:45
answered Apr 16 at 4:40
m_goldbergm_goldberg
91.8k8 gold badges75 silver badges210 bronze badges
91.8k8 gold badges75 silver badges210 bronze badges
add a comment
|
add a comment
|
$begingroup$
Define the votes as lists instead of a function:
SeedRandom[1234];
senatorvote = RandomInteger[-1, 1, 25, 30];
closestvoters[n_] := MaximalBy[Delete[Range[Length[senatorvote]], n],
senatorvote[[n]].senatorvote[[#]] &]
farthestvoters[n_] := MinimalBy[Range[Length[senatorvote]],
senatorvote[[n]].senatorvote[[#]] &]
test:
closestvoters[1]
13, 20
farthestvoters[1]
5
$endgroup$
add a comment
|
$begingroup$
Define the votes as lists instead of a function:
SeedRandom[1234];
senatorvote = RandomInteger[-1, 1, 25, 30];
closestvoters[n_] := MaximalBy[Delete[Range[Length[senatorvote]], n],
senatorvote[[n]].senatorvote[[#]] &]
farthestvoters[n_] := MinimalBy[Range[Length[senatorvote]],
senatorvote[[n]].senatorvote[[#]] &]
test:
closestvoters[1]
13, 20
farthestvoters[1]
5
$endgroup$
add a comment
|
$begingroup$
Define the votes as lists instead of a function:
SeedRandom[1234];
senatorvote = RandomInteger[-1, 1, 25, 30];
closestvoters[n_] := MaximalBy[Delete[Range[Length[senatorvote]], n],
senatorvote[[n]].senatorvote[[#]] &]
farthestvoters[n_] := MinimalBy[Range[Length[senatorvote]],
senatorvote[[n]].senatorvote[[#]] &]
test:
closestvoters[1]
13, 20
farthestvoters[1]
5
$endgroup$
Define the votes as lists instead of a function:
SeedRandom[1234];
senatorvote = RandomInteger[-1, 1, 25, 30];
closestvoters[n_] := MaximalBy[Delete[Range[Length[senatorvote]], n],
senatorvote[[n]].senatorvote[[#]] &]
farthestvoters[n_] := MinimalBy[Range[Length[senatorvote]],
senatorvote[[n]].senatorvote[[#]] &]
test:
closestvoters[1]
13, 20
farthestvoters[1]
5
answered Apr 16 at 6:46
RomanRoman
15.9k1 gold badge22 silver badges55 bronze badges
15.9k1 gold badge22 silver badges55 bronze badges
add a comment
|
add a comment
|
$begingroup$
In addition to Roman's post, here is a method to compute all closest and farthest voters to all senators at once as follows; this should be about to 2 orders of magnitude faster than Roman's code.
SeedRandom[1234];
senatorvote = RandomInteger[-1, 1, 2500, 3000];
A = senatorvote.senatorvote[Transpose];
closestvoters = Flatten[Position[#, Max[#]]] & /@ (A - 2 DiagonalMatrix[Diagonal[A]]);
farthestvoters = Flatten[Position[#, Min[#]]] & /@ A;
By computing A
first, you can take greatest advantage of the linear algebra capabilities of your hardware. Afterwards, you have to find only the minimum and maximum positions per row. So the closest voters to senator n
will be written into closestvoters[[n]]
.
Since Position
is somewhat slow in finding positions of integers in a vector (notice that Position
can do a lot more than that which comes at a cost), here a faster implementation utilizing an undocumented function:
closestvoters = Random`Private`PositionsOf[#, Max[#]] & /@ (A - 2 DiagonalMatrix[Diagonal[A]]);
farthestvoters = Random`Private`PositionsOf[#, Min[#]] & /@ A;
$endgroup$
add a comment
|
$begingroup$
In addition to Roman's post, here is a method to compute all closest and farthest voters to all senators at once as follows; this should be about to 2 orders of magnitude faster than Roman's code.
SeedRandom[1234];
senatorvote = RandomInteger[-1, 1, 2500, 3000];
A = senatorvote.senatorvote[Transpose];
closestvoters = Flatten[Position[#, Max[#]]] & /@ (A - 2 DiagonalMatrix[Diagonal[A]]);
farthestvoters = Flatten[Position[#, Min[#]]] & /@ A;
By computing A
first, you can take greatest advantage of the linear algebra capabilities of your hardware. Afterwards, you have to find only the minimum and maximum positions per row. So the closest voters to senator n
will be written into closestvoters[[n]]
.
Since Position
is somewhat slow in finding positions of integers in a vector (notice that Position
can do a lot more than that which comes at a cost), here a faster implementation utilizing an undocumented function:
closestvoters = Random`Private`PositionsOf[#, Max[#]] & /@ (A - 2 DiagonalMatrix[Diagonal[A]]);
farthestvoters = Random`Private`PositionsOf[#, Min[#]] & /@ A;
$endgroup$
add a comment
|
$begingroup$
In addition to Roman's post, here is a method to compute all closest and farthest voters to all senators at once as follows; this should be about to 2 orders of magnitude faster than Roman's code.
SeedRandom[1234];
senatorvote = RandomInteger[-1, 1, 2500, 3000];
A = senatorvote.senatorvote[Transpose];
closestvoters = Flatten[Position[#, Max[#]]] & /@ (A - 2 DiagonalMatrix[Diagonal[A]]);
farthestvoters = Flatten[Position[#, Min[#]]] & /@ A;
By computing A
first, you can take greatest advantage of the linear algebra capabilities of your hardware. Afterwards, you have to find only the minimum and maximum positions per row. So the closest voters to senator n
will be written into closestvoters[[n]]
.
Since Position
is somewhat slow in finding positions of integers in a vector (notice that Position
can do a lot more than that which comes at a cost), here a faster implementation utilizing an undocumented function:
closestvoters = Random`Private`PositionsOf[#, Max[#]] & /@ (A - 2 DiagonalMatrix[Diagonal[A]]);
farthestvoters = Random`Private`PositionsOf[#, Min[#]] & /@ A;
$endgroup$
In addition to Roman's post, here is a method to compute all closest and farthest voters to all senators at once as follows; this should be about to 2 orders of magnitude faster than Roman's code.
SeedRandom[1234];
senatorvote = RandomInteger[-1, 1, 2500, 3000];
A = senatorvote.senatorvote[Transpose];
closestvoters = Flatten[Position[#, Max[#]]] & /@ (A - 2 DiagonalMatrix[Diagonal[A]]);
farthestvoters = Flatten[Position[#, Min[#]]] & /@ A;
By computing A
first, you can take greatest advantage of the linear algebra capabilities of your hardware. Afterwards, you have to find only the minimum and maximum positions per row. So the closest voters to senator n
will be written into closestvoters[[n]]
.
Since Position
is somewhat slow in finding positions of integers in a vector (notice that Position
can do a lot more than that which comes at a cost), here a faster implementation utilizing an undocumented function:
closestvoters = Random`Private`PositionsOf[#, Max[#]] & /@ (A - 2 DiagonalMatrix[Diagonal[A]]);
farthestvoters = Random`Private`PositionsOf[#, Min[#]] & /@ A;
edited Apr 16 at 7:37
answered Apr 16 at 7:27
Henrik SchumacherHenrik Schumacher
68.7k5 gold badges98 silver badges191 bronze badges
68.7k5 gold badges98 silver badges191 bronze badges
add a comment
|
add a comment
|
Thanks for contributing an answer to Mathematica Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmathematica.stackexchange.com%2fquestions%2f195264%2fdot-products-and-for-loops%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
$begingroup$
Why should I avoid the For loop in Mathematica? mathematica.stackexchange.com/questions/134609/…
$endgroup$
– Roman
Apr 16 at 6:49