MATLAB: Modulus Function for Summing Odd Integers [closed] - matlab

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
How would you use the modulus function to sum odd integers?
I was able to view the odd integers but couldn't sum them together.

If I am interpreting your question correctly, you don't want to use the modulus function to sum odd integers, but you want to use the modulus function to help you determine what is an odd integer and sum only those numbers in your data set that are odd integers. If you read this at a first glance, this is confusing because it sounds like you want to use the modulus function and the modulus function only to sum values.
Let's say you have integers in a vector called data. What you can do is if you want to check to see whether an integer is odd, you check to see if the remainder once you divide by 2 is 1 (i.e. num mod 2 == 1). Recall the definition of an odd number. This means that you can take any integer, and represent it such that you can find an integer k where the number can be represented as 2k + 1. Therefore, if you were to take the modulus of this number with 2 as the base, you would get 1 as the answer. Bear in mind that this does not apply to negative numbers.
As such, these are the steps that I would suggest that you do:
Find all of the locations where the modulo function gives you 1.
Use these locations and sum up your data.
Here is the code I would use:
function sumOdd = sumOddNumbers(data)
%// Step #1
ind = mod(data, 2) == 1;
%// Step #2
sumOdd = sum(data(ind));
Here we are creating a function that will help us do that. You specify data as input into your function, and the output (sumOdd) will contain the sum of the odd numbers. As such, take this code and save it to a new .m file. Also, make sure you call it sumOddNumbers.m. Next, make sure you set your working directory to be where you have placed this file.
Let's do a quick example:
data = 1 : 10; %// Create an array going from 1 to 10
sumOdd = sumOddNumbers(data); %// Answer should be 25... why?
Now let's go through the function step by step and see why the answer is 25.
ind = mod(data, 2) == 1; %// Should give us an array s.t. [1 0 1 0 1 0 1 0 1 0]
sumOdd = sum(data(ind)); %// Should sum over the following array [1 3 5 7 9]
%// Answer is 25

Related

Splitting Vector into Sub-vectors MATLAB

I am trying to figure out how to split a vector in matlab into subvectors.
I am solving a differential equation numerically using dde23. When You do this the length of the solution vector changes. Thus, I am finding it not so easy to use the mat2cell command that many people suggest.
All I am trying to do is split (as evenly as possible) a vector of length N into an arbitrary amount of sub-vectors whose length may vary depending on the length of the time vector. I am doing this so then I can find the maximum value of each vector on in each interval.
If I understand the question, maybe you can try to split it by using code below
dataset=[ 1 2 3 4 5 6 7 8 9 10]
splitpoint = randi[2 length(dataset)-1]
subset1 = dataset(1,1:splitpoint)
splitpoint = randi[length(subset1)+1 length(dataset)-1]
subset2 = dataset(1,length(subset1)+1:splitpoint)
After that you can choose where to finish and accept rest of it for last subset or you can define one list to hold each subset in the row of the list. So you can define while loop to handle it automatically by defining stop_criteria.

Retrieve a specific permutation without storing all possible permutations in Matlab

I am working on 2D rectangular packing. In order to minimize the length of the infinite sheet (Width is constant) by changing the order in which parts are placed. For example, we could place 11 parts in 11! ways.
I could label those parts and save all possible permutations using perms function and run it one by one, but I need a large amount of memory even for 11 parts. I'd like to be able to do it for around 1000 parts.
Luckily, I don't need every possible sequence. I would like to index each permutation to a number. Test a random sequence and then use GA to converge the results to find the optimal sequence.
Therefore, I need a function which gives a specific permutation value when run for any number of times unlike randperm function.
For example, function(5,6) should always return say [1 4 3 2 5 6] for 6 parts. I don't need the sequences in a specific order, but the function should give the same sequence for same index. and also for some other index, the sequence should not be same as this one.
So far, I have used randperm function to generate random sequence for around 2000 iterations and finding a best sequence out of it by comparing length, but this works only for few number of parts. Also using randperm may result in repeated sequence instead of unique sequence.
Here's a picture of what I have done.
I can't save the outputs of randperm because I won't have a searchable function space. I don't want to find the length of the sheet for all sequences. I only need do it for certain sequence identified by certain index determined by genetic algorithm. If I use randperm, I won't have the sequence for all indexes (even though I only need some of them).
For example, take some function, 'y = f(x)', in the range [0,10] say. For each value of x, I get a y. Here y is my sheet length. x is the index of permutation. For any x, I find its sequence (the specific permutation) and then its corresponding sheet length. Based on the results of some random values of x, GA will generate me a new list of x to find a more optimal y.
I need a function that duplicates perms, (I guess perms are following the same order of permutations each time it is run because perms(1:4) will yield same results when run any number of times) without actually storing the values.
Is there a way to write the function? If not, then how do i solve my problem?
Edit (how i approached the problem):
In Genetic Algorithm, you need to crossover parents(permutations), But if you crossover permutations, you will get the numbers repeated. for eg:- crossing over 1 2 3 4 with 3 2 1 4 may result something like 3 2 3 4. Therefore, to avoid repetition, i thought of indexing each parent to a number and then convert the number to binary form and then crossover the binary indices to get a new binary number then convert it back to decimal and find its specific permutation. But then later on, i discovered i could just use ordered crossover of the permutations itself instead of crossing over their indices.
More details on Ordered Crossover could be found here
Below are two functions that together will generate permutations in lexographical order and return the nth permutation
For example, I can call
nth_permutation(5, [1 2 3 4])
And the output will be [1 4 2 3]
Intuitively, how long this method takes is linear in n. The size of the set doesn't matter. I benchmarked nth_permutations(n, 1:1000) averaged over 100 iterations and got the following graph
So timewise it seems okay.
function [permutation] = nth_permutation(n, set)
%%NTH_PERMUTATION Generates n permutations of set in lexographical order and
%%outputs the last one
%% set is a 1 by m matrix
set = sort(set);
permutation = set; %First permutation
for ii=2:n
permutation = next_permute(permutation);
end
end
function [p] = next_permute(p)
%Following algorithm from https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order
%Find the largest index k such that p[k] < p[k+1]
larger = p(1:end-1) < p(2:end);
k = max(find(larger));
%If no such index exists, the permutation is the last permutation.
if isempty(k)
display('Last permutation reached');
return
end
%Find the largest index l greater than k such that p[k] < p[l].
larger = [false(1, k) p(k+1:end) > p(k)];
l = max(find(larger));
%Swap the value of p[k] with that of p[l].
p([k, l]) = p([l, k]);
%Reverse the sequence from p[k + 1] up to and including the final element p[n].
p(k+1:end) = p(end:-1:k+1);
end

Cutting a 250000 value long vector into pieces of 50 and summing them with MATLAB [duplicate]

This question already has an answer here:
Summing up till a certain interval
(1 answer)
Closed 8 years ago.
I have a dataset (which is an hdf5 file) that contains a list of 250000 values, all quite small (sub 10). I want to cut this into 5000 pieces, so 50 each, and I want to individually sum the values in each of these 5000 pieces. I then want to create a histogram of these 5000 pieces, so I need to store them as well.
I am trying to do this using MATLAB, as my very limited programming skills have been developed using this, and it seems suitable for these purposes. Now, I haven't gotten very far, but what I have done so far is:
for n = 1:50:249951
% CR check before (before pumping?)
ROdata = h5read('hdf5file', '/data', [n], [n+49]);
sum(ROdata)
end
Of course, this does not yet store the values of the sum for each n. But more importantly, it does not work. For n = 1, all is fine, and I get the correct value. But already for n = 51, (so summing 51-100), I do not get the correct sum. What's going wrong here?
How should I store these (not working) sums?
Are you looking for something like this?
I assumed you already read your data and you have a 250000x1 vector.
%example data
data = randi(42,1,250000);
% rearranges your vector in groups of 50
A = reshape(data,[],5000);
% sums every column of your reshaped vector
sums = sum(A,1);
hist(sums,5000)

How can i increase speed of for loop in matlab? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to read the value of pixcels in image result to compare this value with some
I use to for loop
function GrdImg= GrdLbp(VarImg,mapping,LbpImg)
tic
p=mapping.samples;
[Ysize,Xsize]=size(result);
GImg=zeros(Ysize,Xsize);
temp=[];
cnt=1;
for n=0:p-1
temp(cnt)=2^n;
temp(cnt+1)=(2^p)-1-(2^n);
cnt=cnt+2;
end
for i=1:Ysize
i
for j=1:Xsize
if isempty(find(result(i,j)==temp(:,:)))==1
GImg(i,j)=sqrtm(Vresult(i,j));
end
end
end
but it works too slow, Could you help me what can I use instead of for loop?
Thanks a lot
You didn't really give enough information to answer your question - since, as was stated in the comments, you aren't doing anything with the values in the loop right now. So let me give you a few ideas:
1) To compare all the pixels with a fixed value, and return the index of all pixels greater than 90% of the maximum:
threshold = 0.9 * max(myImage(:));
prettyBigPixels = find(myImage > threshold);
2) To set all pixels < 5% of max to zero:
threshold = 0.05 * max(myImage(:));
myImage(myImage < threshold) = 0;
In the first case, the find command returns all the indices (note - you can access a 2D matrix of MxN with a single index that goes from 1 to M*N). You can use ind2sub to convert to the individual i, j coefficients if you want to.
In the second case, putting (myImage < threshold) as the index of the matrix is called logical indexing - it is very fast, and will access only those elements that meet the criterion.
If you let us know what you're actually doing with the values found we can speed things up more; because right now, the net result of your code is that when the loop is finished, your value Temp is equal to the last element - and since you did nothing in the loop we can rewrite the whole thing as
Temp = pixel(end);
EDIT Now that you show what you are doing in your inner loop, we can optimize more. Behzad already showed how to speed up the computation of the vector temp - nothing to add there, it's the right way to do it. As for the two nested loops, which are likely the place where most time is spent, you can find all the pixels you are interested in with a single line:
pixelsOfInterest = find(~ismember(result(:), temp(:)));
This will find the index of pixels in result that do not occur in temp. You can then do
GImg(pixelsOfInterest) = sqrt(result(pixelsOfInterest));
These two lines together should replace the functionality of everything in your code from for i=1:Ysize to the last end. Note - your variables seem to be uninitialized, and change names - sometimes it's result, sometimes it's Vresult. I am not trying to debug that; just giving you a fast implementation of your inner loop.
As of question completely edited I answer new rather than edit my former answer, by the way.
You can improve your code in some ways:
1. instead of :
for n=0:p-1
temp(cnt)=2^n;
temp(cnt+1)=(2^p)-1-(2^n);
cnt=cnt+2;
end
use this one:
temp=zeros(1,2*p);
n=0:p-1;
temp(1:2:2*p)=2.^n; %//for odd elements
temp(2:2:2*p)=2^p-1-2.^n; %//for even elements (i supposed p>1)
2.when code is ready for calculating and not for debugging or other times, NEVER make some variables to print on screen because it makes too long time (in cpu cycles) to run. In your code there are some variables like i that prints on screen. remove them or end up them by ;.
3.You can use temp(:) in last rows because temp is one-dimensional
4.Different functions are for different types of variables. in this code you can use sqrt() instead of sqrtm(). it may be slightly faster.
5. The big problem in this code is in your last comparison, if non elemnt of temp matrix is not equal with result specific element then do something! its hard to make this part improved unless knowing the real aim of the code! you may be solve the problem in other algorithm that has completely different code. But if there is no way, so use it in this way (nested loops) Good Luck!
It seems your image is grayscle or monocolor , because Temp=pixel(i,j) gives a number not 3-numbers by the way.
Your question has not more explanation so I think in three type of numbers that you are comparison with.
compare with a constant number
compare with a series of numbers
compare with a two dimensional matrix of numbers
If first or third one is your need, solution is very easy (absolutely in third one, size of matrix must be equal to pixel size)
Comparison with a number (c is number or two-dimensional array)
comp=pixel - c;
But if second one is your need, you can first reshape pixel to one-dimensional matrix then compare it with the series of number s (absolutely length of this serie must be equal to product of pixel rows number and columns number; you can re-reshape pixel matrix after comparison to primary two dimensional matrix.
Comparison with a number serie s
pixel_temp = reshape(pixel,1,[]);
comp = pixel_temp - s;
pixel_compared = reshape(pixel_temp,size(pixel,1),size(pixel,2)); % to re-reshape to primary size

Using rand in matlab to produce numbers between limits [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is there a way in Matlab using the pseudo number generator to generate numbers within a specific range?
I want to get 20 random integer numbers between -10 and 10 and I thought of using the rand function in matlab.
I thought of myltiplying by ten and then finding a way to get only the ones between -10 and 10 and use an iteration for each of the other numbers that is outside the limits [-10,10] to get a new number inside the limits.
Is there a better, faster way?
Use
randomIntegers = randi([-10,10],[20,1])
to generate a vector of random integers between -10 and 10.
Although Jonas' solution is really nice, randi isn't in some of the early versions of MATLAB. I believe all versions have rand. A solution using rand would be:
randomIntergers = floor(a + (b-a+1) .* rand(20,1));
where [a,b] is the range of values you want a distribution over.
If you are use round(a + (b-a)) you will have a nonuniform effect on the values of 'a' and 'b'. This can be confirmed using the hist() function. This is because the domain that maps into 'a' and 'b' is half the size for all other members of the range.