Is there any way in Matlab to generate a 5000 x 1000 matrix of random numbers in which:
MM = betarnd(A,B,1,1000);
but A and B are vectors (1 x 5000). I get the following error message:
??? Error using ==> betarnd at 29
Size information is inconsistent.
I want to avoid a loop like the following one:
for ii = 1 : 1000
MM(:,ii) = betarnd(A,B);
end
Thanks!
You can repeat A and B (vectors of size 1x5000) to obtain matrices of size 1000x5000 in which all rows are equal, and use those matrices as inputs to betarnd. That way you get a result of size 1000x5000 in which column k contains 1000 random values with parameters A(k) and B(k).
The reason is that, according to the documentation (emphasis mine):
R = betarnd(A,B) returns an array of random numbers chosen from the
beta distribution with parameters A and B. The size of R is the common size of A and B if both are arrays.
So, use
MM = betarnd(repmat(A(:).',1000,1), repmat(B(:).',1000,1));
Related
l1=length(A)
l2=length(L)
%Residual
V=A*X-L
S= (V'*P*V)/(6-2);
%adjusted values
Z=V+L
%plot of observed valued of y
plot(X,L)
%plot of adjusted value of Y
plot(X,Z);
%Covariance Matrices for all Given Quantities can be Obtained by:
Cov_X= S*inv(N)
Cov_La=S*(A*N*A')
Cov_V= S*(inv(P)-A*inv(N)*A')
the output is
HA01
l1 =
6
l2 =
6
V =
-16.7888
-31.4848
110.0764
-3.8431
-51.1036
-6.8562
Z =
1.0e+03 *
0.9685
1.0886
1.2161
1.2905
1.3390
1.4506
Error using plot
Vectors must be the same length.
Error in HA01 (line 24)
plot(X,L)
i expected i accidently created different sized vectors etc but length are same yet it refuses to plot. please help i need to submit this in couple of hours.
length will tell you how many elements its has, but not its shape.
If you do size(X) and size(L) you will likely see that one is, say, 1x6 and the other one 6x1. Transpose one of them so they are the same size, not the same length.
I have to calculate maximum of every unique pair of elements in matrix. So here is my code:
resultsMat = [
6 4 4;
0 2 6;
7 7 1;
5 1 73
];
copyMat = resultsMat;
for i=1:size(resultsMat,1)
for j=1:size(resultsMat,2)
for q=1:size(resultsMat,1)
for p=1:size(resultsMat,2)
if i== q && j ~= p
a = max(resultsMat(i,j),copyMat(q,p))
end
end
end
end
end
The problem comes when I try to store values in a matrix. For example:
[val ind] = max(resultsMat(i,j),copyMat(q,p))
This throws an error:
Error using max
MAX with two matrices to compare and two output arguments is not supported.
Error in Untitled2 (line 18)
[a, b] = max(resultsMat(i,j),copyMat(q,p))
How to store values from a = max(resultsMat(i,j),copyMat(q,p)) in a matrix?
You need a larger (probably multi-dimensional) matrix, as every (i,j) location has a maximum vs any (q,p) location. This means that for every element in your first matrix, you obtain a full matrix of the same size. Saving as
matrix_with_results(i,j,q,p) = a
would do this. Then, given any combination of i,j,q,p, it returns the maximum.
Be sure to preallocate
matrix_with_results = zeros(size(resultsMat,1),size(resultsMat,2),size(resultsMat,1),size(resultsMat,2))
for speed.
Two notes:
Don't use i or j as indices/variables names, as they denote the imaginary unit. Using those can easily lead to hard to debug errors.
Initialise matrix_with_results, i.e. tell MATLAB how large it will be before going into the loop. Otherwise, MATLAB will have to increase its size every iteration,which is very slow. This is called preallocation.
I would like to generate an array which contains all ordered samples of length k taken from a set of n elements {a_1,...,a_n}, that is all the k-tuples (x_1,...,x_k) where each x_j can be any of the a_i (repetition of elements is allowed), and whose total number is n^k.
Is there a built-in function in Matlab to obtain it?
I have tried to write a code that iteratively uses the datasample function, but I couldn't get what desired so far.
An alternative way to get all the tuples is based on k-base integer representation.
If you take the k-base representation of all integers from 0 to n^k - 1, it gives you all possible set of k indexes, knowing that these indexes start at 0.
Now, implementing this idea is quite straightforward. You can use dec2base if k is lower than 10:
X = A(dec2base(0:(n^k-1), k)-'0'+1));
For k between 10 and 36, you can still use dec2base but you must take care of letters as there is a gap in ordinal codes between '9' and 'A':
X = A(dec2base(0:(n^k-1), k)-'0'+1));
X(X>=17) = X(X>=17)-7;
Above 36, you must use a custom made code for retrieving the representation of the integer, like this one. But IMO you may not need this as 2^36 is quite huge.
What you are looking for is ndgrid: it generates the grid elements in any dimension.
In the case k is fixed at the moment of coding, get all indexes of all elements a this way:
[X_1, ..., X_k] = ndgrid(1:n);
Then build the matrix X from vector A:
X = [A(X_1(:)), ..., A(X_k(:))];
If k is a parameter, my advice would be to look at the code of ndgrid and adapt it in a new function so that the output is a matrix of values instead of storing them in varargout.
What about this solution, I don't know if it's as fast as yours, but do you think is correct?
function Y = ordsampwithrep(X,K)
%ordsampwithrep Ordered samples with replacement
% Generates an array Y containing in its rows all ordered samples with
% replacement of length K with elements of vector X
X = X(:);
nX = length(X);
Y = zeros(nX^K,K);
Y(1,:) = datasample(X,K)';
k = 2;
while k < nX^K +1
temprow = datasample(X,K)';
%checknew = find (temprow == Y(1:k-1,:));
if not(ismember(temprow,Y(1:k-1,:),'rows'))
Y(k,:) = temprow;
k = k+1;
end
end
end
Suppose in MATLAB I have a real matrix A which is n x m and a binary matrix B of the same size. The latter matrix defines the optimization set (all indices for which the element of B equals one): over this set I would like to find the maximal element of A. How can I do this?
The first idea I had is that I consider C = A.*B and look for the maximal element of C. This works fine for all matrices A which have at least one positive element, however it does not work for matrices with all negative elements.
You can do
C = A(B==1);
to give you an array of just the values of A corresponding to a value of 1 in B. And
max( C )
will give you the maximum value of A where B is 1
With this method you don't run into a problem when all values of A are negative as the zeros don't appear in C.
Obviously you can condense this to
desiredValue = max(A(B(:)==1));
I am using the colon operator to make sure that the result of A(B(:)==1) is a column vector - if B is all ones I am not sure if Matlab would return a vector or a nxm matrix (and I can't confirm right now).
update to get the index of the value, you can do:
f = find(B==1);
[m mi] = max(A(f));
maxIndex = f(mi);
And to get that back to the 2D elements:
[i j] = ind2sub(size(A), maxIndex);
I am currently trying to code up a function to assign probabilities to a collection of vectors using a histogram count. This is essentially a counting exercise, but requires some finesse to be able to achieve efficiently. I will illustrate with an example:
Say that I have a matrix X = [x1, x2....xM] with N rows and M columns. Here, X represents a collection of M, N-dimensional vectors. IN other words, each of the columns of X is an N-dimensional vector.
As an example, we can generate such an X for M = 10000 vectors and N = 5 dimensions using:
X = randint(5,10000)
This will produce a 5 x 10000 matrix of 0s and 1s, where each column is represents a 5 dimensional vector of 1s and 0s.
I would like to assign a probability to each of these vectors through a basic histogram count. The steps are simple: first find the unique columns of X; second, count the number of times each unique column occurs. The probability of a particular occurrence is then the #of times this column was in X / total number of columns in X.
Returning to the example above, I can do the first step using the unique function in MATLAB as follows:
UniqueXs = unique(X','rows')'
The code above will return UniqueXs, a matrix with N rows that only contains the unique columns of X. Note that the transposes are due to weird MATLAB input requirements.
However, I am unable to find a good way to count the number of times each of the columns in UniqueX is in X. So I'm wondering if anyone has any suggestions?
Broadly speaking, I can think of two ways of achieving the counting step. The first way would be to use the find function, though I think this may be slow since find is an elementwise operation. The second way would be to call unique recursively as it can also provide the index of one of the unique columns in X. This should allow us to remove that column from X and redo unique on the resulting X and keep counting.
Ideally, I think that unique might already be doing some counting so the most efficient way would probably be to work without the built-in functions.
Here are two solutions, one assumes all values are either 0's or 1's (just like the example in your description), the other does not. Both codes should be very fast (more so the one with binary values), even on large data.
1) only zeros and ones
%# random vectors of 0's and 1's
x = randi([0 1], [5 10000]); %# RANDINT is deprecated, use RANDI instead
%# convert each column to a binary string
str = num2str(x', repmat('%d',[1 size(x,1)])); %'
%# convert binary representation to decimal number
num = (str-'0') * (2.^(size(s,2)-1:-1:0))'; %'# num = bin2dec(str);
%# count frequency of how many each number occurs
count = accumarray(num+1,1); %# num+1 since it starts at zero
%# assign probability based on count
prob = count(num+1)./sum(count);
2) any positive integer
%# random vectors with values 0:MAX_NUM
x = randi([0 999], [5 10000]);
%# format vectors as strings (zero-filled to a constant length)
nDigits = ceil(log10( max(x(:)) ));
frmt = repmat(['%0' num2str(nDigits) 'd'], [1 size(x,1)]);
str = cellstr(num2str(x',frmt)); %'
%# find unique strings, and convert them to group indices
[G,GN] = grp2idx(str);
%# count frequency of occurrence
count = accumarray(G,1);
%# assign probability based on count
prob = count(G)./sum(count);
Now we can see for example how many times each "unique vector" occurred:
>> table = sortrows([GN num2cell(count)])
table =
'000064850843749' [1] # original vector is: [0 64 850 843 749]
'000130170550598' [1] # and so on..
'000181606710020' [1]
'000220492735249' [1]
'000275871573376' [1]
'000525617682120' [1]
'000572482660558' [1]
'000601910301952' [1]
...
Note that in my example with random data, the vector space becomes very sparse (as you increase the maximum possible value), thus I wouldn't be surprised if all counts were equal to 1...