I have written the following 'matlab' code that is supposed to return the maximum value in an array:
function m = maxi(a)
maximum = a(1,1);
[m,n]=size(a);
for i=1:m
for j=1:n
if a(i,j)>=maximum
maximum = a(i,j)
else
maximum = maximum;
end
end
end
m = maximum;
end
The case here is that the returned result seems to be the maximum number in each iteration. How can I return only one value, which is the maximum value?
Thanks.
To find the maximum value in an array, it is advisable to use the built-in function max. Note that max operates along the first dimension of the array by default; to find the overall max, you may therefore want to pass your array as a vector:
overallMax = max(array(:));
Really, it's not recommended to re-implement built-ins if performance is at all important. However, for educational purposes, it can be useful to reverse-engineer code.
Your function runs fine for me, though I would suggest that you iterate over linear indices (similar to how you transform the array to a vector above). This way it will work for an array of arbitrary dimensionality.
function mx = maxi(a)
mx = a(1);
for ii = 1:numel(a)
if a(ii) > mx
mx = a(ii);
end
end
Related
I am struggling to work on a divide-and-conquer problem as I can't quite wrap my head around it.
Lets say we have some array X[1:n]. How would we go about finding the min-prefixarray X[1:k] where 1 ≤ k ≤ n and the prefix is defined as X[1]×X[2]×...×X[n] for an array of real numbers?
My approach so far has been:
function min_prefix(array[1:n],n)
begin
if array.length == 1 then
return n, array[0], array[0]
endif
integer best_k, real b_total, total = min_prefix([1:n-1],n-1)
new_total = total*array[n]
if new_total < b_total then
return n, new_total, new_total
endif
return best_k, b_total, new_total
end
I dont think this is a valid divide-and-conquer solution as I still have to iterate over every element in the array.
Edit:
The best example I could think of:
Consider the array {-1,2,2,2} the min-prefix would be k=3 as, when all the elements are multiplied together the resultant answer is -6.
However if we then consider the array {-1,2,-2,2} then the min prefix would be k=1 as k[0]*k[1] = -2 multiplying the 3rd element onwards would only make the number larger.
The algorithm to find the "minimal prefix product" is, basically, to calculate all possible prefixes and find the minimum among them. This can be done in linear time, and not faster.
Pseudocode:
min_pref_l = 1
min_pref_v = arr[0]
prev_f = arr[0]
for i in 1 until arr.length:
pref_v *= arr[i]
if pref_v < min_pref_v:
min_pref_v = pref_v
min_pref_l = i + 1
return min_pref_v, min_pref_l
The strangest part of the question is the "divide and conquer" requirement. I think, if you squint hard enough and look at this algorithm, you can probably say, that it's "divide and conquer", as for calculating the prefix of length i it uses the previously calculated prefix of length i-1.
To illustrate that, the algorithm could be rewritten as a recursive function:
# min_prefix returns tuple of three values:
# First two define the minimal prefix of length ≤ i, as the pair of (value, length)
# Third is the product of the prefix of length i
fun min_prefix(i: int) -> (int, int, int):
if i == 0:
return arr[0], 1, arr[0]
prev_min_l, prev_min_v, prev_v = min_prefix(i-1)
v = prev_v * arr[i]
if v < prev_min_v:
return i+1, v, v
else:
return prev_min_l, prev_min_v, v
# program result
return min_prefix(arr.length - 1)
Note:
in the recursive variant the space complexity went from O(1) to O(n), the function can be rewritten as tail recursive to avoid that
corner cases, such as empty array and product overflow were not considered intentionally, to simplify the code
I have two/more arrays. I want to form a new array which is sorted from the two/more array.
I dont want to combine the arrays and later sort. I wanted to get it on the go.
Time complexity is considered.
Any programming language/algorithm is fine.
so basically you need to find for each position in the new array the smallest remaining value.
The input are the arrays a and b with n and m elements. Find min value in both arrays. compare the two values and set the smaller one to max Value in its array to prevent that it is found again. Set the min value in c.
Pseudocode:
merge(a[n],b[m]){
c[n+m];
for (i = 0, i < n+m; i++){
aMin = getMinValue(a);
bMin = getMinValue(b);
if(aMin < bMin) setMinValueToMax(a,aMin)
else setMinValueToMax(b,bMin)
c[i] = min(aMin,bMin)
}
return c;
}
Here n is the size of the bigger array.
GetMinValue will run in O(n), just iterate over all elements. SetMinValueToMax will run in O(n) as well if you don't save the index. The for-loop will be in O(n). The body of the for is 0(3n) (2 x getMinValue + setMinValueToMax). In big O const factors can be removed which leads to a runtime of O(n^2).
I have the task of creating a piece of matlab code that uses the sieve of Eratosthenes to find the list of prime numbers up to N. I have created a loop that finds the non primes and then finds the index value of them in the list of 2 to N. How do I get my program to take these index values element by element and set the corresponding positions in my zero matrix to one?
Also for my assignment I cannot use the in built isprime functions.
My code so far:
function [p,c] = sieve(N)
N = input('Please type an integer greater than 1: ');
a = ones(1,N); %Non-primes are set to 0
for k = 2:N
How does k:k:end work, I'm guessing it adds k until it reaches N.
Thanks
Assuming your matrix of zeros is called "numbersthatareprime" and your prime indices are called "primeindices":
numbersthatareprime(primeindices)=1
That's just a matter of using your array to index into your vector. As such, create a vector of all zeros that is N in length, then assuming you have the list of prime numbers up to N which is called prim, just do:
vec = zeros(1, N);
vec(prim) = 1;
OK
As OP may still be confused, I'll just give a new answer (not dissimilar to my previous wrong one)
x=zeros(100,1);
for i=2:100;
x(2*i:i:end)=1;
end; find(~x)
You just need to go from 2*i rather than i....
You don't really need a matrix. Just a list of values!
X=zeros(10000,1);
for i=2:100
X(i:i:end) = 1
end
Here, the indexing i:i:end means
[2,4,6,8,...] when i==2
[3,6,9,...] when i==3
etc
So it sets all the multiples of 2, then all the multiples of 3 etc., creating your seive.
Note that you only need to go up to sqrt(N).
Then you can just do find(X) to get the primes!
I am a complete beginner at Octave!
I am struggling to figure out the minimum value from the array mse_array. I keep getting an error saying: "subscript indices must be either positive integers less than 2^31 or logicals"
Could someone help me? Here's my code:
function randomLines(data1, data2)
mse_array = []
A = rand(2,10)*100
for i = columns(A)
max = A (1, i)
min = A (2, i)
m = (max-min)/0.16
p = [m min];
array_function_values = polyval(p,data2);
current_mse = mseFunction(data1,array_function_values);
mse_array(end + 1) = current_mse
endfor
min_value = min(mse_array)
endfunction
Q: How to find a minimum from an array in Octave?
octave has built-in self-describing documentation to use once in doubts
A: Always re-read both help min and doc min
octave-3.2.4.exe:1> help min
`min' is a function from the file C:\Octave\3.2.4_gcc-4.4.0\libexec\octave\3.2.4\oct\i686-pc-mingw32\max.oct
-- Loadable Function: min (X)
-- Loadable Function: min (X, Y)
-- Loadable Function: min (X, Y, DIM)
-- Loadable Function: [W, IW] = min (X)
For a vector argument, return the minimum value. For a matrix
argument, return the minimum value from each column, as a row
vector, or over the dimension DIM if defined. For two matrices
(or a matrix and scalar), return the pair-wise minimum. Thus,
min (min (X))
returns the smallest element of X, and
min (2:5, pi)
=> 2.0000 3.0000 3.1416 3.1416
compares each element of the range `2:5' with `pi', and returns a
row vector of the minimum values.
For complex arguments, the magnitude of the elements are used for
comparison.
If called with one input and two output arguments, `min' also
returns the first index of the minimum value(s). Thus,
[x, ix] = min ([1, 3, 0, 2, 0])
=> x = 0
ix = 3
See also: max, cummin, cummax
Re-defining (thus rendering un-usable) elements as reserved words just increases troubles. Try to use your own naming convention, that will not harm the rest of the system -- i.e. anArrayMinimumVALUE or aSmallestVALUE, rather than "killing" the Octave function min() by creating a variable named by accident as "also" min
There are several things wrong with your code. Here are a few to get you started.
The error is probably occurring at this line:
min_value = min(mse_array)
You're using mse_array as an index into min, but the values in mse_array are likely to valid array indices as the error states. (I'm guessing at this purely based on the name of the variable, mse_array, which appear to be from some form of mean squared error calculation.) It's important to check the line number and everything else in error messages.
Another issue in that your for loop only evaluates once. The columns function will return the scalar number of columns of A. Thus your your loop declaration is equivalent to:
for i = 10
In other words, the code will only look at the last column of A. You probably want to use:
for i = 1:columns(A)
Lastly, it's a bad idea to overwrite the built-in min and max functions in Octave with your own variable names. If you overwrite the built-in min function, you won't be able to use it anymore directly until you call clear min (alternatively, you can call builtin, but you should avoid that). Instead, just choose better variable names.
...using an iterative procedure (no hash table)?
It's not homework. And by mode I mean the most frequent number (statistical mode). I don't want to use a hash table because I want to know how it can be done iteratively.
OK Fantius, how bout this?
Sort the list with a RadixSort (BucketSort) algorithm (technically O(N) time; the numbers must be integers). Start at the first element, remember its value and start a count at 1. Iterate through the list, incrementing the count, until you reach a different value. If the count for that value is higher than the current high count, remember that value and count as the mode. If you get a tie with the high count, remember both (or all) numbers.
... yeah, yeah, the RadixSort is not an in-place sort, and thus involves something you could call a hashtable (a collection of collections indexed by the current digit). However, the hashtable is used to sort, not to calculate the mode.
I'm going to say that on an unsorted list, it would be impossible to compute the mode in linear time without involving a hashtable SOMEWHERE. On a sorted list, the second half of this algorithm works by just keeping track of the current max count.
Definitely sounds like homework. But, try this: go through the list once, and find the largest number. Create an array of integers with that many elements, all initialized to zero. Then, go through the list again, and for each number, increment the equivalent index of the array by 1. Finally, scan your array and return the index that has the highest value. This will execute in roughly linear time, whereas any algorithm that includes a sort will probably take NlogN time or worse. However, this solution is a memory hog; it'll basically create a bell plot just to give you one number from it.
Remember that many (but not all) languages use arrays that are zero-based, so when converting from a "natural" number to an index, subtract one, and then add one to go from index to natural number.
If you don't want to use a hash, use a modified binary search trie (with a counter per node). For each element in the array insert into the trie. If it already exists in the trie, increment the counter. At the end, find the node with the highest counter.
Of course you can also use a hashmap that maps to a counter variable and will work the same way. I don't understand your complaint about it not being iterative... You iterate through the array, and then you iterate through the members of the hashmap to find the highest counter.
just use counting sort and look into array which store the number occurrences for each entity.h store the number occurrences for each entity.
I prepared two implementations in Python with different space and time complexity:
The first one uses "occurence array" is O(k) in terms of time complexity and S(k+1) in terms of space needed, where k is the greatest number in input.
input =[1,2,3,8,4,6,1,3,7,9,6,1,9]
def find_max(tab):
max=tab[0]
for i in range(0,len(tab)):
if tab[i] > max:
max=tab[i]
return max
C = [0]*(find_max(input)+1)
print len(C)
def count_occurences(tab):
max_occurence=C[0]
max_occurence_index=0
for i in range(0,len(tab)):
C[tab[i]]=C[tab[i]]+1
if C[tab[i]]>max_occurence:
max_occurence = C[tab[i]]
max_occurence_index=tab[i]
return max_occurence_index
print count_occurences(input)
NOTE: Imagine such pitiful example of input like an array [1, 10^8,1,1,1], there will be array of length k+1=100000001 needed.
The second one solution assumes, that we sort our input before searching for mode. I used radix sort, which has time complexity O(kn) where k is the length of the longest number and n is size of the input array. And then we have to iterate over whole sorted array of size n, to determine the longest subset of numbers standing for mode.
input =[1,2,3,8,4,6,1,3,7,9,6,1,9]
def radix_sort(A):
len_A = len(A)
mod = 5 #init num of buckets
div = 1
while True:
the_buckets = [[], [], [], [], [], [], [], [], [], []]
for value in A:
ldigit = value % mod
ldigit = ldigit / div
the_buckets[ldigit].append(value)
mod = mod * 10
div = div * 10
if len(the_buckets[0]) == len_A:
return the_buckets[0]
A = []
rd_list_append = A.append
for b in the_buckets:
for i in b:
rd_list_append(i)
def find_mode_in_sorted(A):
mode=A[0]
number_of_occurences =1
number_of_occurences_canidate=0
for i in range(1,len(A)):
if A[i] == mode:
number_of_occurences =number_of_occurences +1
else:
number_of_occurences_canidate=number_of_occurences_canidate+1
if A[i] != A[i-1]:
number_of_occurences_canidate=0
if number_of_occurences_canidate > number_of_occurences :
mode=A[i]
number_of_occurences =number_of_occurences_canidate+1
return mode#,number_of_occurences
s_input=radix_sort(input)
print find_mode_in_sorted(s_input)
Using JavaScript:
const mode = (arr) => {
let numMapping = {};
let mode
let greatestFreq = 0;
for(var i = 0; i < arr.length; i++){
if(numMapping[arr[i]] === undefined){
numMapping[arr[i]] = 0;
}
numMapping[arr[i]] += 1;
if (numMapping[arr[i]] > greatestFreq){
greatestFreq = numMapping[arr[i]]
mode = arr[i]
}
}
return parseInt(mode)
}