I wrote the following problem in Matlab to get the first 3 digits of a number.
Let x be a real number.
function [y]=mifl(x) % mifl=my float
s=num2str(x);
y=sscanf(s(1:4),'%f');
end
So function mifl returns the first 3 digits of a number.
For example,
mifl(pi)=3.14
But when I tried to apply this function to all the values of the vector v I got "Index exceeds matrix dimensions". I can't figure out why.
I used
v=linspace(0.1, 99.9, 1000);
w=[]
for i=1:5
w(i)=mifl(v(i))
end
That's when I get the "Index exceeds matrix dimensions".
At the end, what I want is, given a vector
v=linspace(0.1, 99.9, 1000);
to get a vector
w=[mifl(0.1),...mifl(99.9)]
The reason is because you are specifying a number in your function that doesn't have three significant digits. Specifically, try 0.1 from your vector. This doesn't have 3 digits and so you get an out of bounds error because you're assuming it does.
As such, in your function, check the length of the string and ensure that there are 4 characters to extract. If not, then get whatever is available:
function [y]=mifl(x) % mifl=my float
s=num2str(x);
m = min(numel(s), 4); %// Change
y=sscanf(s(1:m),'%f');
end
If you try the above, your code should now work.
I'd like to also suggest that you pre-allocate your arrays before populating them for speed.
Specifically:
v=linspace(0.1, 99.9, 1000);
w=zeros(numel(v),1);
for i=1:numel(v)
w(i)=mifl(v(i));
end
w is initialized to be an array of 0s that is as long as v, then we'll go through each value in v and call mifl, then store this result in the corresponding location in w.
You can use Matlabs rand function.
y = round(x,3,'significant');
This will return the first 3 significant digits of each number in a vector x. This code will also be easy for another person to comprehend since round is a built in Matlab function, which is used for rounding. The argument 'significant' should be clear enough. This will also work for numbers larger than 100, which makes it more general. That is of course if it was 3 significant digits you were after and not the first three digits in the number. In that case this will not work. The number 1001 would then be 1000 and not 100, which your solution would give.
Related
Write a C program using the arrays to eliminate the duplicate numbers. Generate 50 random
numbers between 50 and 150 using rand function. Insert the random numbers to the array with
a size 50. As each number is generated, print it only if it’s not a duplicate of a number already
generated. Provide for the “worst-case” in which all 50 numbers are different.
This how I would approach it:
The easier way for me is to have a frequency table (an array of size 151), since you are dealing with a short range of numbers.
Initialize the array with 0's (Could use memset() here).
Get a random number within your range (lets say n)
Check that array[n] is 0.
If it is, print the number and increment the array by one (array[n]++)
If not, print an error
Repeat until you've read 50 numbers
I am trying to solve the below question.
You are given an array of n numbers and q queries. For each query you have to print the floor of the expected value(mean) of the subarray from L to R.
First line contains two integers N and Q denoting number of array elements and number of queries.
Next line contains N space seperated integers denoting array elements.
Next Q lines contain two integers L and R(indices of the array).
Print a single integer denoting the answer.*
I have replaced print() with stdout.write() and input() with stdin.readline().
from sys import stdin, stdout
x,y=map(int,stdin.readline().split())
array=[int(x) for x in stdin.readline().split()]
result=[]
sum=0
for i in range(y):
l,r=map(int,stdin.readline().split())
for i in range(l-1,r):
sum = sum + array[i]
result.append(sum//(r-l+1))
sum=0
for i in result:
stdout.write(str(i)+"\n")
The time taken by my code is about 8 secs, to solve the challenge time limit is 1.5 secs
This type of problem is usually pretty simple if you store the sums from 1-i in the ith value of the array, like so:
from sys import stdin, stdout
x,y=map(int,stdin.readline().split())
array=[int(x) for x in stdin.readline().split()]
sums[0] = array[0]
sums = [sum[i-1]+array[i] for i in range(1,len(array))]
result=[]
for i in range(y):
l,r=map(int,stdin.readline().split())
result.append((sums[r-1]-sums[l-1])//(r-l+1))
for i in result:
stdout.write(str(i)+"\n")
By doing presummation it changes the speed of the program from O(N^2) to O(N) which should be much faster.
Remove the append operation. It is a costly operation and is unecessary since you don't reuse the results. Instead, do directily:
for i in range(l-1,r):
sum = sum + array[i]
stdout.write(str(sum//(r-l+1))+"\n")
By doing like this you avoid go through the second loop too.
If you try, please report here the time taken.
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'm a beginner still learning to us C and I don't know how to find the factors of an int that are the closest to each other.
For example, if the input was the number 6, the output would be [2,3]. If the input was 24, then the output would be [4,6].
Is there a way to do this? Any help would be appreciated.
The algorithm to do this is simple; take the square root of your number as an integer (you want to truncate, not round). Test if that value is a factor of your input; if so, your input divided by that number are your answer. Otherwise, subtract 1 from your previous value and try again.
In code (the array literal is the wrong syntax, but the theory is correct):
//this code assumes that your input is > 0, will not work otherwise
function int[] getClosestFactors(int input) {
int testNum = (int)sqrt(input);
while (input % testNum != 0) {
testNum--;
}
return {testNum, input / testNum};
}
Basically, you know that in any pair of factors, the lowest factor must be less than or equal to the square root. So if you start at the integer equal to or less than the square root of your input, and count down, the first factor you find will be the smaller of the pair of closest factors. This terminates for all integers > 0 because you will eventually reach 1, which is a factor of all other numbers.
im doing a short course in c programming and i have been so busy lately with my other classes and and helping my bother prepare for his wedding (as im his best man)that I have fallen behind and need help. any help towards this short assignment would be much appreciated as im not familiar at all with matrixs and its due in a few days.
the assignment is to Sum of third upper anti-diagonal a squared matrix .
i have been given this information:
The matrix should be a square, integer matrix of size N. In this assignment the matrix will be stored
in a 1d block of memory. You will have to convert between the conceptual 2d matrix addressing and
1d block addressing with pointer arithmetic.
Note on random numbers:
rand() function returns the next integer a sequence of pseudo-random integers in the range
[0, RAND_MAX]. RAND_MAX is a very large number and varies from system to system. To get an
integer in the range [min, max]:
(int)((min)+rand()/(RAND_MAX+1.0) * ((max)-(min)+1))
srand(SEED) is used to set the seed for rand. If srand() is called with the same seed value, the
sequence of pseudo-random numbers is repeated. To get different random numbers each time a
programme runs use time(NULL) as the seed. Rand is in stdlib.h, which needs to be included.
The program should be structured as follows.
#define N 32 // Matrix size
#define MYSEED 1234 // Last 4 digits of your student number.
int *initialise( ) // Allocate memory for the matrix using malloc
// Initialise the matrix with random integers x, 1≤ x ≤ 9
// Use 'MYSEED' as the seed in the random generator.
// Return a pointer to the matrix
void print_matrix(int *) // Print matrix on screen
int compute_diagonal(int *) // Compute your required calculation using pointer arithmetic.
// (square bracket [ ] array indexes shouldn't be used)
// Return the solution.
void finalise(int *) //free the allocated memory.
int main() // The main function should print the solution to screen.
Without doing your homework assignment for you, here's a tip:
Make a functions that abstract storing and retrieving values out of the matrix. One of the signatures should look a lot like this:
int retrieve(int* matrix, int row, int col);
Ok since this is homework and you still have a few days I will not give you an exact answer here. But I will give you some thoughts with which it should be pretty easy to come to your answer.
Indexing a matrix 1D-way: You are not allowed to use matrix[x][y] here, but only a one-dimensional array. So just take a minute and think of how the index (x,y) can be computed within a 1D array. Keep in mind that C stores elements rowwise (i.e. the elements matrix[0][0], matrix[0][1], matrix[0][2] refer to matrix[0], matrix[1], matrix[2]). It is a simply forumla in terms of X, Y and N
Filling the matrix randomly is easy, the function to create a random int is already given, just walk the matrix along and fill every element
Adding the third anti-upper diagonal. This isn really a programming question. Just sketch a small matrix on a piece of paper and see what elements you have to add. Look at their indices and than combine your newly gained knowledge with your result from my point 1 and you will know what to add up
Edit: Since you are not allowed to use the bracket operator, keep in mind that matrix[5] is the same as *(matrix+5).
I think it's fair to tell you this ;)