Dot products and For-loops Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm...
Why is my conclusion inconsistent with the van't Hoff equation?
ListPlot join points by nearest neighbor rather than order
How do pianists reach extremely loud dynamics?
Bete Noir -- no dairy
How come Sam didn't become Lord of Horn Hill?
How to react to hostile behavior from a senior developer?
Identifying polygons that intersect with another layer using QGIS?
What LEGO pieces have "real-world" functionality?
Why is "Consequences inflicted." not a sentence?
Why are there no cargo aircraft with "flying wing" design?
What does "fit" mean in this sentence?
English words in a non-english sci-fi novel
Can a USB port passively 'listen only'?
Fundamental Solution of the Pell Equation
Output the ŋarâþ crîþ alphabet song without using (m)any letters
Is it ethical to give a final exam after the professor has quit before teaching the remaining chapters of the course?
Storing hydrofluoric acid before the invention of plastics
2001: A Space Odyssey's use of the song "Daisy Bell" (Bicycle Built for Two); life imitates art or vice-versa?
51k Euros annually for a family of 4 in Berlin: Is it enough?
Single word antonym of "flightless"
Is the Standard Deduction better than Itemized when both are the same amount?
How to run gsettings for another user Ubuntu 18.04.2 LTS
What's the purpose of writing one's academic biography in the third person?
Seeking colloquialism for “just because”
Dot products and For-loops
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
Announcing the arrival of Valued Associate #679: Cesar Manara
Unicorn Meta Zoo #1: Why another podcast?Why should I avoid the For loop in Mathematica?Maximizing functions with Which statementsNested For Loops that result in no outputHow 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 MapVariable Increments in a TableWhat is p[a] forFormatting a list of values and dependent formatting of corresponding errors listSymmetry of a Dot with functions with argumentsFor Loop and Sum
$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
19 hours ago
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 21 hours ago
m_goldberg
88.8k873200
88.8k873200
asked 22 hours ago
H. S.H. S.
261
261
$begingroup$
Why should I avoid the For loop in Mathematica? mathematica.stackexchange.com/questions/134609/…
$endgroup$
– Roman
19 hours ago
add a comment |
$begingroup$
Why should I avoid the For loop in Mathematica? mathematica.stackexchange.com/questions/134609/…
$endgroup$
– Roman
19 hours ago
$begingroup$
Why should I avoid the For loop in Mathematica? mathematica.stackexchange.com/questions/134609/…
$endgroup$
– Roman
19 hours ago
$begingroup$
Why should I avoid the For loop in Mathematica? mathematica.stackexchange.com/questions/134609/…
$endgroup$
– Roman
19 hours ago
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/3.0/"u003ecc by-sa 3.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 21 hours ago
answered 21 hours ago
m_goldbergm_goldberg
88.8k873200
88.8k873200
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 19 hours ago
RomanRoman
5,49111131
5,49111131
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 18 hours ago
answered 18 hours ago
Henrik SchumacherHenrik Schumacher
60.3k583169
60.3k583169
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
19 hours ago