How to assign x to all elements in a vector for loop - loops

So there's a vector with multiple elements consisting of numbers from 1-10. What I'm trying to do is create a for loop that computes the calculation of x^2 - x for every element in that vector and then sum up all the results.
numbers <- c(9,4,6,4,7,3,6,10,6,4,1,9,1,1,9,8,8,10,3,7,3,7,5,2,3,6,6,2,3,8,7,7,6,8,1,8,5,5,7,3,6,6,7,6,2,1,10,8,10,7)
x <- assign(x, numbers)
for(i in nrow(numbers)){
x[i] = (x[i]^2)-x[i]
y <- sum(x[i])
return(y)
}

Related

A matrix of random numbers but each column and row add up to the same total

I need to generate a matrix 7*7 and with the following rules:
The first and last row and column must contain a set of numbers that add up to a total of 6. And only the numbers 0, 1, 2 can be used randomly.
The other Columns and rows add up (each) to 12 using numbers 0 1 2 3 4 randomly.
There are additional conditions but the ultimate goal is to generate a matrix of numbers similar to this:
I have tried to use a code such as this one:(this is just for the first row)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int i, j, x;
int grille[7][7];
int limV[7], limH[7], copy[7];
srand ((unsigned) time (NULL));
x=0;
for(i=0; i<7; i++){
limV[i]= 0;
limH[i]= 0;
}
while(limH[0]!=6){
limH[0]=0;
for(i=0; i<7; i++){
if(i==0 || i==6){
grille[0][i] = rand()%2;
limH[0] += grille[0][i];
limV[i] = grille[0][i] ;
} else{
grille[0][i] = rand()%3;
limH[0] += grille[0][i];
limV[i] = grille[0][i] ;
}
}
}
return 0;
}
I am not looking for the solution to this algorithm but rather a hint or tips to be able to move forward in my project.
The general idea is:
Fill numbers randomly
Check whether the sums are correct
If not, go to step 1
Or another version, probably more practical:
Fill the border randomly
Check whether the sums on border are correct
If not, go to step 1
Fill the inner 5x5 matrix randomly
Check whether the sums on the inner rows and columns are correct
If not, go to step 4
The probability of stumbling upon a valid matrix by chance is very low but not impractically low. To get an estimate: the probability for 5 randomly chosen numbers to make a sum of 10 is about 12%. There are 10 sums to check, so the probability is 0.12-10 (1 in a billion).
To generate a random number in the range 0...2:
rand() % 3
To generate a random number in the range 0...4:
rand() % 5
To check the sum of numbers in e.g. a column:
bool is_column_sum_correct(int grille[7][7], int column)
{
int sum = 0;
for (int row = 0; row < 7; ++row)
sum += grille[row][column];
int expected_sum = (column == 0 || column == 6) ? 6 : 12;
return sum == expected_sum;
}
Alternatively, you can generate a few valid matrices manually, and swap columns and rows randomly to get a few more variants.
In addition to swapping, there are some other transformations which could make valid matrices. For example:
x x x x x x x x x x
x x x x x x x x x x
x x 0 1 x => x x 1 0 x
x x 1 3 x x x 0 4 x
x x x x x x x x x x
That is, take a 2x2 sub-matrix, add 1 to one of its diagonals, and subtract 1 from the other diagonal.
Repeat these transformations many times, and you will get a very different matrix.

Equation relating the specific index of a value in an array and the size of the array MatLab

I'm trying to come up with an equation that relates the index of a value within a 3D array, to the index of the same array but reshaped into a column vector.
Consider the following.
A = randi([1,10],3,2,2);
A2 = reshape(A,3*2*2,1);
A and A2 have the same number of elements, but the arrangement of the elements is different for each array. If I lay out a possible example for A and A2 here it is clear geometrically how each index lines up.
A(:,:,1) = [9 10; 10 7; 2 1]
A(:,:,2) = [3 10; 6 2; 10 10]
A2 = [9; 10; 2; 10; 7; 1; 3; 6; 10; 10; 2; 10]
Let's say n=1:1:3*2*2, this is an array that is the same length as A2 and numbers each of the elements. The value of A(2,2,2)=2 and has indices [i,j,k]=[2,2,2]. I would like to have an equation relating i, j, k, and n.
I've looked into the built-in functions ind2sub and sub2ind but it seems that I inadvertently shaped my i, j, and k coordinates (which correspond with real x, y, and z points) differently than how MatLab does. This makes it difficult for me to change everything now, and is why I need an equation.
The conversion between 3D index and linear (1D) index is given by:
n=i+(j-1)*M + (k-1)*M*N
The reverse can be obtained recursively as:
k = floor((n-1)/(M*N)) +1
n = n - (k-1)*M*N
j = floor((n-1)/M) + 1
i = n - (j-1)*M
I haven't tested it, but I think it will give you what you are expeccting.

Summing elements from a vector, bounded by certain indices

I have a row vector x in Matlab which contains 164372 components. I now want to group these elements in another vector y, which has to contain 52 components. The first element of the vector y must be the average of the first 164372 / 52 = 3161 elements of the vector x, the second element of y must be the average of the next 3161 elements of x, etc. This continues until I have taken all of the 52 averages of the elements in the vector x and placed them in y.
How can I implement this in Matlab? Is there some built-in function that lets me sum elements from a certain index to another index?
Thank you kindly for any help!
With reshape and mean:
x = rand(1,164372); % example data
N = 52; % block size. Assumed to divide numel(x)
result = mean(reshape(x, numel(x)/N, []), 1)
What this does is: reshape the vector into a 52-row matrix in the usual column-major order, and then compute the mean of each column.

Multiplying vectors of uneven length and summing the result

How can I for every element of a vector calculate several elements from another vector?
For example, x=[1,2] and y=[1,2,3,4] then I need to multiply and sum each element of x with all elements of y, like so;
x = [1,2]
y = [1,2,3,4]
z = [x1*y,x2*y] = [x1*y1+x1*y2+x1*y3+x1*y4,x2*y1+x2*y2+x2*y3+x2*y4]
The vectors can have unlimited elements.
x = randi(10,3,1);
y = randi(10,4,1);
tmp = bsxfun(#times,x.',y); % Pre-R2016b
% tmp = x.'*y; % Post R2016b method
out = sum(tmp(:));
One can use either bsxfun or implicit expansion to create a matrix of numel(x) * numel(y) size and then sum over the flattened array to get to a final result.
You can multiply x with sum of y
result = x * sum(y)

Find subset of size k such that the minimum distance between values is maximum

Suppose i have an array which contain n integers .
How to find subset of size k such that the minimum distance between all pairs of integers in the subset is maximized , i mean they are at farthest distance .
example : array a[]={1,2,6,7,10} and k=3 ,
subset = {1,6,10} , the minimum distance is 4 between 10 and 6 .
Wrong subsets :
{1,7,10} , minimum distance is 3
{1,2,6} , minimum distance is 1
I came up with a solution :
1) sort array
2) select a[0] , now find ceil(a[0]+ x) = Y in array ....and then ceil(Y+ x) and so on k-1 times , also kth element will be a[n-1]
To find x :
dp[i,j] be the x for selecting j elements from first i elements .
Finally we want dp[n][k] which is x
But i am facing problem in finding x .
dp[i,j] = max( min( dp[k,j-1], dp[i]-A[k] ) )
over k=1 to i-1 , i=2 to n , j=2 to i
dp[i][1] = 0 over i = 1 to n
EDIT : I want to correct the dynamic programming solution , though i know x can be found out by binary searching over x .
UPDATE 2 : I have updated the code , but still not getting correct solution . Please point the error .
code : http://ideone.com/J5vvR9
UPDATE 3 : Thanks #Gassa , #Niklas B. and #Fallen for your answers !.
The base should be:
dp[i][1] = INFINITY for i = 1 to n
The reason being that minimum of an empty set is positive infinity.
In practice, any integer larger than the maximum possible a[i] - a[j] for some i and j will suffice as an INFINITY constant.
Additionally, the correct transition would be:
dp[i,j] = max{for k=1 to i-1} (min(dp[k,j-1], a[i]-a[k]))
I think there is no need in finding x if time allows to search for possible values of x. Just add the outer loop which will be a binary search on the answer (that is, the minimum distance, let us call it x).
Once x is fixed, you can greedily pick values starting from a[0]. The next selected value will be such a[i] that i is minimal and a[i] - a[0] >= x. The third one will be a[j] such that j is minimal and a[j] - a[i] >= x, and so on. If you are able to pick at least k values in this fashion, the actual answer is at least the current x; if not, the answer is less than x.
The total running time will be O (n log (C)) where C is the total number of possible values in the array. Say, if the integers in the array are from 0 to 1000000, C will be 1000001 and log (C) (rounded up) will be 20. First, you try x = 500000; if it fails, you are left with the range [0; 500000) for the answer; if not, with the range [500000; 1000000], etc.
Do a binary search over value of X. Then for each such x, write a DP/Greedy function that checks if there's an array with result(maximal distance between elements) more than or equal to X.
Correctness: If for any X, we can have M elements, such that minimum distance between them is greater than or equal to X, then for every x, x < X, at least this same array will server as result. And for any X, if there's no M elements, such that the minimum distance between the elements is greater than or equal to X, then for no x, x > X, M such elements are available. So we can binary search on X.

Resources