I am trying to use a for loop and then sum all of the outputs. I know this is a basic question, but I am not sure if I should be trying to solve this within the loop or using another array.
For example:
for i in 1..100
if foo / 2 == 0
#find the sum of all outputs
end
end
Try this:
(2..100).step(2).inject(:+) #=> 2550
Or:
2.step(100,2).inject(:+) #=> 2550
You can use sum instead of inject(:+) from Ruby 2.4+
I'm not entirely sure what you're asking, but my initial understanding is that you want to sum all of the numbers in a range (1..100) that meet a specific condition. In this case, something divided by 2 cannot equal zero aside from zero itself. I'm wondering if you meant %2, in which case, you're asking to sum all the even numbers in the range 1..100. This can be accomplished by doing the following.
(1..100).select {|x| x if x.even?}.reduce(:+)
Effectively, you want to enumerate over a range and select only the numbers that meet your condition, as specified in the block. Calling reduce and passing it an accumulator.
Related
I have array A (44x1) and B (41x1), and I want to count for both arrays how many times the elements are repeated. And if the repeated values are present in both arrays, I want their counting to be divided (for instance: value 0.5 appears 500 times in A and 350 times in B, so now divide 500 by 350).
I have to do this for bigger arrays as well, so I was thinking about using a looping (but no idea how to do it on MATLAB).
I got what I want on python:
import pandas as pd
data1 = pd.read_excel('C:/Users/Desktop/Python/data1.xlsx')
data2 = pd.read_excel('C:/Users/Desktop/Python/data2.xlsx')
for i in data1['Mag'].value_counts() & data2['Mag'].value_counts():
a = data1['Mag'].value_counts()/data2['Mag'].value_counts()
print(a)
break
Any idea of how to do the same on MATLAB? Thanks!
Since you can enumerate all valid earthquake magnitude values, you could use:
% Make up some data
A=randi([2 58],[100 1])/10;
B=randi([2 58],[20 1])/10;
% Round data to nearest tenth
%A=round(A,1); %uncomment if necessary
%B=round(B,1); %same
% Divide frequencies
validmags=0.2:0.1:5.8;
Afreqs=sum(double( abs(A-validmags)<1e-6 ),1); %relies on implicit expansion; A must be a column vector and validmags must be a row vector; dimension argument to sum() only to remind user; double() not really needed
Bfreqs=sum(double( abs(B-validmags)<1e-6 ),1); %same
Bfreqs./Afreqs, %for a fancier version: [{'Magnitude'} num2cell(validmags) ; {'Freq(B)/Freq(A)'} num2cell(Bfreqs./Afreqs)].'
The last line will produce NaN for 0/0, +Inf for nn/0, and 0 for 0/nn.
You could also use uniquetol, align the unique values of each vector, and divide the respective absolute frequencies. But I think the above approach is cleaner and easier to understand.
How can I check all the values in a Julia array at once? Let's say I have an array like a=[3,4,6,10,55,31,9,10] How can I check if the array has any values greater than 10? Or how can I check if there are repeating values (like the 10 that is contained twice in the sample? I know I can write loops to check this, but I assume Julia has a faster way to check all the values at once.
The functions any and count do this:
julia> a = [3,4,6,10,55,31,9,10]
8-element Array{Int64,1}:
3
4
6
10
55
31
9
10
julia> any(x->x==3, a)
true
julia> count(x->x==10, a)
2
However the performance will probably be about the same as a loop, since loops in julia are fast (and these functions are themselves implemented in julia in the standard library).
If the problem has more structure you can get big speedups. For example if the vector is sorted you can use searchsorted to find matching values with binary search.
Not sure if this had been implemented at the time of previous answers, but the most concise way now would be:
all(a .> 10)
As Chris Rackauckas mentioned, a .> 10 returns an array of booleans, and then all simply checks that all values are true. Equivalent of Python's any and all.
You can also use broadcasted operations. In some cases it's nicer syntax than any and count, in other cases it can be less obvious what it's doing:
boola = a.>10 # Returns an Array{Bool}, true at any value >10
minimum(boola) # Returns false if any are <10
sum(a-10 .== 0) # Finds all values equal to 10, sums to get a count
I've been stuck on this problem. I'd appreciate any help.
The instructions
"Use the .each method on the odds array to print out double the value of each item of the array. In other words, multiply each item by 2.
Make sure to use print rather than puts, so your output appears on one line."
My code
odds = [1,3,5,7,9]
odds.each do |placeholder|
odds *= 2
print odds
end
odds = [1,3,5,7,9]
odds.each do |placeholder|
odds *= 2
print odds
end
Your usage of #each is correct here, but remember that #each receives an ::Enumerable object, the block passed in uses the variable placeholder to encapsulate the value in the ::Array at the current point of the iteration. Therefore you would need to use placeholder to retrieve the value you want to double, and not odds because odds would still be an ::Array within the ::Enumerable function #each.
This code can be written in two lines as follows:
odds = [1,3,5,7,9]
odds.each {|placeholder| print placeholder * 2 }
Strictly speaking, #map would be the preferred method for doing this.
odds.each { |x| print "#{x*2}" }
ruby-ish way:
print odds.map {|x| x*2}.join(' ')
You are trying to multiply the Array odds by two in each iteration in your code. The do |placeholder| means 'for each item in the array, give me the single element and call it placeholder'.
So you would need to use placeholder *= 2.
However, since you aren't mutating the original value in odds, you can shorten your inner block by just print placeholder * 2.
Additionally, while the question might be saying to use :each, :map is much more canonical to what you are doing. Using map would allow you to double each element like so:
odds.map{ |i| i*2 }
odds is your array. placeholder represents a value from the array. Without explicitly providing you the answer, what you want to do is multiply the value by 2, not the array itself.
Here Iam done that on succesfully
odds = [1,3,5,7,9]
odds.each do |x|
x *= 2
print x
end
Below I pasted a small part of my code which covers the question I have. I'm running three for loops in a Unix script. The first loop n just runs over integer values. The second loop k runs over integer values as well, but I change it later for kappa to represent all values divided by 10, in this case the range is 0:0.1:10.
Now, my question concerns the third loop. I am a total beginner with Unix programming so this might be a very basic question, still I can't seem to figure it out. The third loop is supposed to cover an array of predefined values, i.e. p=[0 1/15 1/12 1/10 2/15 1/6 1/5 1/4 1/3]. I have defined jmax as 9 but yet I don't know how to set these corresponding p values to this loop parameter. Basically I would just like to set up an array holding these values and then assign them, can anyone please give me some directions as how to do that?
Please note: due to other use of $j I have to leave the start of the for loop intact!
Code partial:
for ((n=0;n<${nmax};n++)); do # first loop
for ((k=0;k<${kmax};k++)); do # second loop
for ((j=0;j<${jmax};j++)); do # third loop
# specify you job ......
kappa=$(echo "scale=10; ${k}/10" | bc -l)
Many thanks!
This is how you would create an array and loop over it:
# create an array
p=(0 1/15 1/12 1/10 2/15 1/6 1/5 1/4 1/3)
# loop over the elements in the array
for j in "${p[#]}"; do
echo "$j"
done
Take a look at the Arrays chapter of the Advanced Bash-Scripting Guide.
If you do not specifically need an array for your script, and if your array entries do not contain whitespace characters, there is an even easier solution:
# Assign all values that should be looped over to a normal string variable,
# with each value separated by a space
p="0 1/15 1/12 1/10 2/15 1/6 1/5 1/4 1/3"
# Loop over all values in p
for value in p; do
# Access each value in p using $value
done
Can anyone tell me if there is a way (in MATLAB) to check whether a certain value is equal to any of the values stored within another array?
The way I intend to use it is to check whether an element index in one matrix is equal to the values stored in another array (where the stored values are the indices of the elements which meet a certain criteria).
So, if the indices of the elements which meet the criteria are stored in the matrix below:
criteriacheck = [3 5 6 8 20];
Going through the main array (called array) and checking if the index matches:
for i = 1:numel(array)
if i == 'Any value stored in criteriacheck'
%# "Do this"
end
end
Does anyone have an idea of how I might go about this?
The excellent answer previously given by #woodchips applies here as well:
Many ways to do this. ismember is the first that comes to mind, since it is a set membership action you wish to take. Thus
X = primes(20);
ismember([15 17],X)
ans =
0 1
Since 15 is not prime, but 17 is, ismember has done its job well here.
Of course, find (or any) will also work. But these are not vectorized in the sense that ismember was. We can test to see if 15 is in the set represented by X, but to test both of those numbers will take a loop, or successive tests.
~isempty(find(X == 15))
~isempty(find(X == 17))
or,
any(X == 15)
any(X == 17)
Finally, I would point out that tests for exact values are dangerous if the numbers may be true floats. Tests against integer values as I have shown are easy. But tests against floating point numbers should usually employ a tolerance.
tol = 10*eps;
any(abs(X - 3.1415926535897932384) <= tol)
you could use the find command
if (~isempty(find(criteriacheck == i)))
% do something
end
Note: Although this answer doesn't address the question in the title, it does address a more fundamental issue with how you are designing your for loop (the solution of which negates having to do what you are asking in the title). ;)
Based on the for loop you've written, your array criteriacheck appears to be a set of indices into array, and for each of these indexed elements you want to do some computation. If this is so, here's an alternative way for you to design your for loop:
for i = criteriacheck
%# Do something with array(i)
end
This will loop over all the values in criteriacheck, setting i to each subsequent value (i.e. 3, 5, 6, 8, and 20 in your example). This is more compact and efficient than looping over each element of array and checking if the index is in criteriacheck.
NOTE: As Jonas points out, you want to make sure criteriacheck is a row vector for the for loop to function properly. You can form any matrix into a row vector by following it with the (:)' syntax, which reshapes it into a column vector and then transposes it into a row vector:
for i = criteriacheck(:)'
...
The original question "Can anyone tell me if there is a way (in MATLAB) to check whether a certain value is equal to any of the values stored within another array?" can be solved without any loop.
Just use the setdiff function.
I think the INTERSECT function is what you are looking for.
C = intersect(A,B) returns the values common to both A and B. The
values of C are in sorted order.
http://www.mathworks.de/de/help/matlab/ref/intersect.html
The question if i == 'Any value stored in criteriacheck can also be answered this way if you consider i a trivial matrix. However, you are proably better off with any(i==criteriacheck)