Concatenation of Vectors in MATLAB - matlab

I have these 10 vectors in MATLAB, mean(alltmws{l}'), where l is from 1 to 10. The size of each of these vectors is 1X10001. Now I want to store all these values in one vector, one after the other, so that I can calculate and plot the overall mean. How can I do this concatenation? Any help will be greatly appreciated.

If you have, for example,
a{1} = rand(10,1);
a{2} = rand(10,1);
a{3} = rand(10,1);
You can do
A = [a{:}];
A = A(:)
EDIT: The question is ambiguous, but if it is the means that one wants to concatenate and plot, you can do:
% Create example data
data = {};
for k = 1:10
data{k} = rand(100,1);
end
% Compute and plot array of means
mu = []
for k = 1:length(data)
mu(k) = mean(data{k});
end
plot(mu)

If you have a 1x10 cell array, then you can directly do:
concatnatedArray=cell2mat(yourCellArray);
If you have a 10x1 cell array, first transpose it and then apply above technique. This will only work if all the vectors in each cell are of the same length, which the case for you.

Related

Filling in a Cell of Matrices in MATLAB

In Matlab I am trying to create a cell of size 16 x1 where each entry of this cell is a matrix. I have the following equation
$$W_g = exp^{\frac{j{2\pi m}{N}(n+\frac{g}{G}))} \,\,\,\,\,\,\, m,n=0,1,.....(N-1)$$
for this work assume $N=4$ and the index $g$ is the index that refers to the cell element i.e g=0:1:15
W=cell(16,1);
for g=1:16
for m=1:3
for n=1:3
W{g,m,n}= exp((2*pi*j*m/4)* n+(g-1)/16));
end
end
end
How can I make this work? I have two problems with this, you see g starts from 0 and MATLAB doesnt accept index of zero and how to actually define the matrices within the cell.
Thanks
So if I understand you have this equation:
And you just want the following code:
W=cell(16,1);
n = 1:3;
m = 1:3;
N = 4;
for g=1:16
W{g}= exp((2*pi*j.*m/4*N).*n+(g-1)/16);
end
%or the 1 line version:
W = cellfun(#(g) exp((2*pi*j.*m/4*N).*n+(g-1)/16),num2cell([1:16]),'UniformOutput',0);
With matlab you can use the Element-wise multiplication symbol .*
For example:
%A matrix multiplication
A = [2,3]
B = [1,3]';
result = A * B %result = 11
%An element wise multiplication
A = [2,3]
B = [1,3];
result = A .* B %result = [2,9]
First of all, i is the complex number in matlab (sqrt(-1)) not j, and you are correct, matlab is indexed in 1, so simply start counting g at 1, until 16.
Next, create a zero matrix, and calculate all indices accordingly. Something like this should work just fine :
clc
clear all
W=cell(16,1);
for g=1:16;
temp = zeros(3,3);
for m=1:3
for n=1:3
temp (m,n) = exp((2*pi*1i*m/4)* n+g/16);
end
end
W{g} = temp;
end
if you are considering doing much larger operations, consider using linspace to create your m and n indices and using matrix operations

Matlab: store array in matrix?

I have many array (n*1 dimension), how can I do something like
matrix = [];
for i = 1:5
for j =1:5
matrix (i,j) = zeros(n,1); % store a given array to a cell of a matrix
end
end
I find Array of Matrices in MATLAB
But this is store matrices into array, not the otherwise.
Ying Xiong's suggestion is what you want if the vectors are of different lengths. But assuming the number of elements is constant (which they seem to be) you may also use a 3-dimensional array, where each (i,j) element contains a vector in the third dimension, like this:
rows = 5; cols = 5; n = 10; %// Dimensions
matrix = zeros(rows, cols, n); %// Initialize matrix
vector = 1:n; %// Just an example
for ii = 1:rows %// Bad practice to use i as a variable name
for jj = 1:cols %// Bad practice to use j as a variable name
matrix(ii,jj,:) = vector; %// Assignment
end
end
Now each index (i,j) contains the vectors you want, for instance:
squeeze(matrix(1,1,:))
ans =
1
2
3
4
5
6
7
8
9
10
Having all values in a single matrix can be a good thing if you want to do similar operations on all elements, as vectorized approaches are usually very fast in MATLAB. You might want to check out permute, reshape and functions like bsxfun.
Note that you might be able to vectorize the loops, but without knowing the specifics, that's impossible to know.
You need to use cell array.
n = 10;
matrix = cell(5,5);
for i = 1:5
for j = 1:5
matrix{i,j} = zeros(n,1);
end
end

ArrayFun with multiple input

I have a problem while using Arrayfun in Matlab. I have a vector of angles and I want to avoid a for loop and I apply:
rmatrix1 = arrayfun(...
#(x) anglesLoop(iblade, iradius, jradius, ifrequency, x, rot), ...
angles, 'uniformoutput', false);
Where iblade = 1, iradius = 1, jradius = 1, ifrequency = 1 and rot = 0.5.
The function looks like:
%% Angles Loop
function rmatrix = anglesLoop(iblade, iradius, jradius, ifrequency, angles, rot)
global frequency blade
fshifted =(frequency(ifrequency)-angles*rot);
S11 = kaimal(fshifted);
S22 = S11;
r = distance(iradius,jradius,angles);
aux = (3/(2*pi)).*coherence(r).*exp(-1i*angles*ifrequency*blade(iblade)/3);
rmatrix = (sqrt(S11).*sqrt(S22).*aux.*exp(1i*2*pi.*angles.*1/3));
end
with the subfunctions
%% distance for coherence function
function r=distance(x1,x2,theta)
r = sqrt(x1^2+x2^2- 2*x1*x2*cos(theta));
end
And
%% Coherence
function gamma=coherence(r)
global frequency v10 L1
if r==0
gamma=1;
else
gamma=exp(-12.*sqrt((frequency.*r./v10).^2+(0.12.*r./L1).^2));
end
The problem is that when I apply the anglesLoop function in arrayfun I obtain a cell of 64 different arrays whereas I should obtain a vector of 64 which is the angles length.
rmatrix1 should be a vector of 64 elements. Can someone give me some recommendation?
I think the problem is you're asking for 'UniformOutput', false which causes the return to be a cell array. You then simply need to concatenate the contents of the cell array, which you can do with cell2mat. Here's a simpler example. I've got a row vector, and I'm applying a function that turns each element into a 2x2 matrix. I want to end up with all of these small matrices concatenated together.
rowVector = 1:5;
myFcn = #(x) [x, -x; -x, x];
separateMatricesCell = arrayfun(myFcn, rowVector, 'UniformOutput', false);
concatenatedMatrices = cell2mat(separateMatricesCell)

splitting a matrix row-wise and and finding a linear regression coeff

A= [1 1
2 2
3 3
. .
. .
. .
N N]
I have an [N,2] matrix and I need to split it row-wise into some number of [N/4,2] submatrices. Then for each submatrix I need to find linear regression where the first column of each submatrix is my x data and the second column is my y data. The output should be a struct with fields a,b,c,d.... and values of linear regression for each submatrix
First I tried splitting the matrix with mat2cell where k = length(N)/4 and mat = mat2cell(A, [k k k k], [1 1]).
Next I tried converting mat into struct with out = cell2struct(mat,fields,1) where fields = {'col1','col2'} and use
new = structfun(#(x)polyfit(x.col1, x.col2,1), out,'UniformOutput', false)
But I get the error:
Inputs to STRUCTFUN must be scalar structures.
Does anyone know how to do it? Many thanks
The most straightforawrd way (and probably the fastest) to do this is with a good old for loop:
A = [1:64;1:64]'; % Demo data
m = 4;
N = size(A,1);
k = N/m; % Assumes that length is evenly divisible by 4
c = zeros(m,2); % Coefficients
for i = 1:m
c(i,:) = polyfit(A((i-1)*k+1:i*k,1),A(i-1)*k+1:i*k,2),1);
end
Or rather than using cell2struct and structfun you can use cellfun:
A = [1:64;1:64]'; % Demo data
m = 4;
N = size(A,1);
k = N/m; % Assumes that length is evenly divisible by 4
c = cellfun(#(x)polyfit(x(:,1),x(:,2),1).',mat2cell(A,k+zeros(1,m),2),'UniformOutput',false)
or alternatively
Ac = mat2cell(A,k+zeros(1,m),[1 1])
c = cellfun(#(x1,x2)polyfit(x1,x2,1).',Ac(:,1),Ac(:,2),'UniformOutput',false)
You can convert the output of cellfun to a matrix with:
c = [c{:}].'
As for why you're getting the error, your variable out is a 4-by-1 struct array (array of structures) rather than a simple (scalar) structure of arrays. The documentation for structfun points out this requirement in the description of the short function: "Apply function to each field of scalar structure." This video from The MathWorks tries to explain the difference.

Recovering vector in MATLAB for loop

I am running a for loop in MATLAB. Each iteration produces a vector of length different than the vector created in the previous iteration. Is there any why to recover each individual vector? In the end I want to concatenate each of these vectors. My code is something like
for i=1:n
v = zeros(1,i)
end
so after i=n, v will be a one by n vector, but I also want to recover the vectors for any i. In my code, each vector, v, is not a zero row vector, but a vector of varying size. Thanks.
I'd already typed this when Rody's post (+1) came through so figured I might as well post it too. An alternate solution that is very slightly less efficient (I did some timed runs, the differences were marginal) than Rody's but avoids the complicated indexing is:
A = cell(1, n);
for i = 1:n
A{1, i} = zeros(1, i);
end
Soln = cat(2, A{:});
I store the varying length row vectors in a cell array through the loop then concatenate them in the final step.
The simplest way is like so:
w = [];
for i=1:n
v = zeros(1,i);
%# your stuff here
w = [w v];
end
Which produces the vector w, which is the concatenation of all generated vectors v.
Note however that this is slow, since w grows each iteration. A slightly more complicated but more efficient solution would be this:
w = zeros(1, sum(1:n) );
j = 1;
for i=1:n
v = zeros(1,i);
%# your stuff here
w(1, j:j+i-1) = v;
j = j+i;
end