Get numbers in a matrix in different set positions - matlab

I have a matrix 1x5000 with numbers. Now I am interested in getting values from the matrix in different positions, more precisely in six different places of the matrix. The places should be based on the length, these are the numbers I want to get out:
Number in 1/6 of the matrix length
Number in 2/6 of the matrix length
Number in 3/6 of the matrix length
Number in 4/6 of the matrix length
Number in 5/6 of the matrix length
Number in 6/6 of the matrix length
These values could be printed out in another matrix, so assume the matrix is 1x5000, 3/6 would give the number in the middle of the matrix. I am new in Matlab and therefore the help is much appreciated!

Since your question is unclear I can try to give you an example.
First of all you can use numel function to get matrix's size.
It's easy to get necessary element in Matlab: you can address directly to any element if you know its number (index). So:
x(100) returns 100th element.
Now you got size and know what to do. Last moment - what to do if numel(x) / 6 return non integer?
You can use rounding functions: ceil, floor or round.
index = ceil(numel(x)/6) %if you want NEXT element always
result = x(index)
Next step: there are a lot of ways to divide data. For example now you have just 6 numbers (1/6, 2/6 and so on) but what if there are 1000 of them? You can't do it manually. So you can use for loop, or you can use matrix of indexes or perfect comment Stewie Griffin.
My example:
divider = [6 5 4 3 2 1] % lets take 1/6 1/5 1/4 1/3 1/2 and 1/1
ind = ceil( numel(x)./divider)
res = x(ind)

The colon notation in MATLAB provides an easy way to extract a range of elements from v:
v(3:7) %Extract the third through the seventh elements
You could either manually input range or use a function to convert fractions into suitable ranges

Related

How to generate all possible nxm arrays, if each element is binary (can only take on 0 or 1). Preferably in matlab

I am essentially trying to generate all possible nxm matrices. I have seen some codes in R and Python that kind of does this with a single function, but I cant find anything similar for matlab :(
here's a way to do that in matlab:
n=4;
m=3;
for c=0:2^(n*m)-1
A(:,c+1)=str2double(split(dec2bin(c,n*m),'',1));
end
A(1,:)=[]; A(end,:)=[];
A=reshape(A,n,m,[]);
the logic, it doesnt matter if it is an nxm array or a 1D vector of length nxm, we can later reshape the vector to an nxm array (last line). Then, the # of possible permutation for a binary string of Length L is just all the decimal # from 0 to 2^L-1 transformed to binary string of length nxm. This is what the dec2bin(...) function does. Then we get a long string (for example '010001010111') that needs to be split to individual elements('0','1',...) , so we can later convert this strings to numbers using str2double. The split(...) function does that but generates NaN at the edges, so we get rid of them in the row before the last one...
so for this example I chose n=4, m=3, which generates just 2^(nxm)=4096 possible array...
you can see them if if you try A(:,:,j) with j being a # from 1 to 4096

Accessing the layers of a multidimensional array and performing some function on each layers

I have this code
A = unidrnd(2,100,30)-1;
B = reshape(A, 100, 3, 10);
B is a multidimensional array with 10 layers of 100x3 Matrices. Now I want to perform this code,
C = length(nonzeros(all(B,2)))/100;
where the function on the right hand side of the code is suppose to generate 10 values corresponding to the result of the 10 layers, but all I get is a single value. The right hand of the code checks how many rows are all 1's. It takes the number of rows that are all 1's and divides it by 100 to obtain the fraction of the number of rows that are all 1's.
How can I obtain the result of every 100 x 3 layers of the 3D matrix using the single line of code I have shown above such that I do not have to use a loop? The result C had to be array of the results as expected.
You started out well. all(B,2) is good, it gives you the 100x1x10 matrix that's 1 where the corresponding rows are all 1's and 0 otherwise.
nonzeros, however, simply lists all of the nonzero elements of the entire matrix, in your case, a string of 1's, completely disregarding the dimensions of the array. You'd get the same results with nonzeros(A(:)) as with nonzeros(A).
[Note: nnz(A) would get you the same results as length(nonzeros(A)), but that's not what we want to do anyway.]
Since your matrix is binary (the output of all is a logical array), we can count the number of non-zero elements by summing the matrix elements. And sum gives us a dimension argument just like all, so we just sum the columns that all gave us.
C = sum(all(B,2),1)/100;
This gives you a 1x1x10 array of percentages. If you wanted that to just be a normal vector, you could use squeeze.
C = squeeze(sum(all(B,2),1)/100);

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

How do I efficiently multiply every 2 columns and sum the row

Maybe I should just go with a for loop but I want to see if there is a more efficient/faster way to do it.
I have a matrix of numbers, let's say 10x10. I want to multiply 1,1 by 1,2, then 1,3 times 1,4, etc and then sum those results for row 1. Then move to the next row and do the same thing. The end result would be a vector of 10.
It is possible for this matrix to be 1000x1000 so I want it to be as fast as possible. Thanks!
I would use
v = sum(M(:,1:2:end-1).*M(:,2:2:end),2);
Here M(:,1:2:end-1).*M(:,2:2:end) does multiplication: every element of an odd-numbered column of M is multiplied by its neighbor to the right. (This assumes even number of columns, otherwise the process you described is ill-defined.) Then every row is added up by the sum command.
On my computer, doing this for a 1000 by 1000 matrix takes 0.04 seconds.

Using ranges in Matlab/Octave matrices

Let's say I want to create an 100x100 matrix of which every row
contains the elements 1-100
A = [1:100; 1:100; 1:100... n]
Obviously forming a matrix is a bad idea, because it would force me to
create 100 rows of range 1:100.
I think I could do it by taking a 'ones' array and multiplying every
row by a vector... but I'm not sure how to do it
a = (ones(100,100))*([])
??
Any tips?
You can use the repeat matrix function (repmat()). You code would then look like this:
A = repmat( 1:100, 100, 1 );
This means that you're repeating the first argument of repmat 100 times vertically and once horizontally (i.e. you leave it as is horizontally).
You could multiply a column vector of 100 1s with a row vector of 1:100.
ones(3,1)*(1:3)
ans =
1 2 3
1 2 3
1 2 3
Or you could use repmat ([edit] as Phonon wrote a few seconds before me [/edit]).
Yes, repmat is the easy solution, and even arguably the right solution. But knowing how to visualize your aim and how to create something that yields that aim will give long term benefits in MATLAB. So try other solutions. For example...
cumsum(ones(100),2)
bsxfun(#plus,zeros(100,1),1:100)
ones(100,1)*(1:100)
cell2mat(repmat({1:100},100,1))
and the boring
repmat(1:100,100,1)