understand how reshape function forms matrix - matlab

let us consider following matrix for illustration
A=rand(6,3)
A =
0.3500 0.8308 0.7537
0.1966 0.5853 0.3804
0.2511 0.5497 0.5678
0.6160 0.9172 0.0759
0.4733 0.2858 0.0540
0.3517 0.7572 0.5308
to total we have 6*3=18 element,after apply reshape function
reshape(A,2,9)
ans =
0.3500 0.2511 0.4733 0.8308 0.5497 0.2858 0.7537 0.5678 0.0540
0.1966 0.6160 0.3517 0.5853 0.9172 0.7572 0.3804 0.0759 0.5308
clearly if we look on original array,then we can easily see that rows of these new matrix is same as
B=A(:)'
B =
Columns 1 through 9
0.3500 0.1966 0.2511 0.6160 0.4733 0.3517 0.8308 0.5853 0.5497
Columns 10 through 18
0.9172 0.2858 0.7572 0.7537 0.3804 0.5678 0.0759 0.0540 0.5308
>> B(1:2:18)
ans =
0.3500 0.2511 0.4733 0.8308 0.5497 0.2858 0.7537 0.5678 0.0540
so in reshape(A,m,n) where m*n must be total element,m represent starting form first element in first column,increment in columns until nth element?also when i have tried
reshape(A,3,4)
Error using reshape
To RESHAPE the number of elements must not change.
it gives me error,so whenever i choose n,m must be number of elements in array divided by n right?thanks in advance

Matlab stores its matrices column-wise. This means internally it basically is just one array where all the columns are concatenated. The shape of the matrix is stored seperately.
I don't quite understand your last question, because your matrix A has 18 entries, but you try to reshape it into a matrix with 3*4=12 entries
I hope this helped you

Reshape is for reordering elements as explained in #alex answer (and of course the number of elements must not change!). If you want to resize a matrix, use indexing:
Examples
A = rand(6,6) % Start matrix
A =
0.0113 0.5362 0.3510 0.7220 0.2084 0.8344
0.5013 0.9770 0.5221 0.5743 0.8442 0.8102
0.1214 0.0390 0.9594 0.1385 0.9038 0.6081
0.2480 0.9165 0.1986 0.3692 0.5135 0.6154
0.3631 0.9843 0.3697 0.5964 0.6437 0.6901
0.9978 0.8182 0.1990 0.8273 0.6811 0.2464
Use '[]' to remove lines or columns
A(2:3, :) = [] % This removes 2nd and 3rd lines
A(:, [2 5]) = [] % This further removes 2nd and 5th columns
A =
0.0113 0.3510 0.7220 0.8344
0.2480 0.1986 0.3692 0.6154
0.3631 0.3697 0.5964 0.6901
0.9978 0.1990 0.8273 0.2464
Use indexing for zero padding
AA = zeros(6, 6); % Build larger matrix the size you want ...
AA([1 2 4 6], [2 3 5 6]) = A % Place elements of `A` inside `AA` as you wish ...
AA =
0.0000 0.0113 0.3510 0.0000 0.7220 0.8344
0.0000 0.2480 0.1986 0.0000 0.3692 0.6154
0.0000 0.0000 0.0000 0.0000 0.0000 0.0000
0.0000 0.3631 0.3697 0.0000 0.5964 0.6901
0.0000 0.0000 0.0000 0.0000 0.0000 0.0000
0.0000 0.9978 0.1990 0.0000 0.8273 0.2464
With indexing you can also play around to create bigger/smaller matrices.
A([4 4 1 1 2 3], end:-1:1)
ans =
0.2464 0.8273 0.1990 0.9978
0.2464 0.8273 0.1990 0.9978
0.8344 0.7220 0.3510 0.0113
0.8344 0.7220 0.3510 0.0113
0.6154 0.3692 0.1986 0.2480
0.6901 0.5964 0.3697 0.3631

Related

How do i perform operations on matrix rows while keeping the matrix intact?

Question/problem summary:
Create a 10 by 10 matrix whose first column is the numbers 1,2,3,4,5,6,7,8,9,10
the next column contains the squares of first column: 1, 4, 9,...,100
the third column contains the 3rd power of first column: 1, 8, 27,..., 1000.
the 10th column contains the 10th power of the first column.
Background:
This is for a class assignment, intro to analytical programming. I have tried the following code, but i am not sure why it is not giving the correct output. Any advice or suggestions is appreciated.
row1 = [1:10]
tenXtenMatrix = repmat(row1,10,1)
[row col] = size(tenXtenMatrix)
for i=2:row
for j=1:col
tenXtenMatrix(i,:).^i
end
end
what is expected:
1 2 3 4 5 6 7 8 9 10
1 4 9 16 25 36 49 64 81 100
1 8 27 64 125 216 343 512 729 1000
1 16 81 256 625 1296 2401 4096 6561 10000
etc..
what i got:
0.0000 0.0000 0.0000 0.0001 0.0010 0.0060 0.0282 0.1074 0.3487 1.0000
0.0000 0.0000 0.0000 0.0001 0.0010 0.0060 0.0282 0.1074 0.3487 1.0000
0.0000 0.0000 0.0000 0.0001 0.0010 0.0060 0.0282 0.1074 0.3487 1.0000
0.0000 0.0000 0.0000 0.0001 0.0010 0.0060 0.0282 0.1074 0.3487 1.0000
etc...
Using implicit expansion:
x = 1:10
A = x.^(x.')
Where:
.^ is the element-wise power operator
.' is the transpose operator
More informations about implicit expansion here.
Fixes:
you run on j and not using it.
you calculate the power but not updating the matrix
row1 = [1:10];
tenXtenMatrix = repmat(row1,10,1);
[row col] = size(tenXtenMatrix);
for i=2:row
tenXtenMatrix(i,:) = tenXtenMatrix(i,:).^i;
end

Changing correlation matrix into covariane matrix Matlab

I'm trying to change a correlation matrix into co-variance matrix...
Importing some data, I found the co-variance (sigma_a)
sigma_a = (sigma_d + (mu_d'+1)*(mu_d+1)).^N - (mu_d'+1).^N *(mu_d+1).^N;
Which returns...
0.1211 0.0231 0.0422 0.0278 0.0411 0.0354 0.0289 0.0366 0.0343 0.0165
0.0231 0.0788 0.0283 0.0242 0.0199 0.0248 0.0219 0.0199 0.0253 0.0140
0.0422 0.0283 0.1282 0.0339 0.0432 0.0366 0.0321 0.0399 0.0420 0.0216
0.0278 0.0242 0.0339 0.0554 0.0261 0.0294 0.0312 0.0269 0.0297 0.0164
0.0411 0.0199 0.0432 0.0261 0.0849 0.0289 0.0271 0.0371 0.0317 0.0173
0.0354 0.0248 0.0366 0.0294 0.0289 0.0728 0.0293 0.0400 0.0339 0.0149
0.0289 0.0219 0.0321 0.0312 0.0271 0.0293 0.0454 0.0276 0.0309 0.0135
0.0366 0.0199 0.0399 0.0269 0.0371 0.0400 0.0276 0.0726 0.0356 0.0162
0.0343 0.0253 0.0420 0.0297 0.0317 0.0339 0.0309 0.0356 0.0715 0.0198
0.0165 0.0140 0.0216 0.0164 0.0173 0.0149 0.0135 0.0162 0.0198 0.0927
Then I found the correlation matrix (rho)
rho = inv(sqrt(diag(diag(sigma_a))))*sigma_a*inv(sqrt(diag(diag(sigma_a))));
Which returns...
1.0000 0.2365 0.3388 0.3396 0.4050 0.3772 0.3897 0.3899 0.3686 0.1556
0.2365 1.0000 0.2812 0.3656 0.2437 0.3274 0.3658 0.2631 0.3377 0.1638
0.3388 0.2812 1.0000 0.4027 0.4141 0.3792 0.4199 0.4133 0.4382 0.1985
0.3396 0.3656 0.4027 1.0000 0.3809 0.4638 0.6221 0.4246 0.4728 0.2295
0.4050 0.2437 0.4141 0.3809 1.0000 0.3681 0.4366 0.4732 0.4068 0.1948
0.3772 0.3274 0.3792 0.4638 0.3681 1.0000 0.5093 0.5499 0.4707 0.1813
0.3897 0.3658 0.4199 0.6221 0.4366 0.5093 1.0000 0.4797 0.5428 0.2079
0.3899 0.2631 0.4133 0.4246 0.4732 0.5499 0.4797 1.0000 0.4936 0.1971
0.3686 0.3377 0.4382 0.4728 0.4068 0.4707 0.5428 0.4936 1.0000 0.2435
0.1556 0.1638 0.1985 0.2295 0.1948 0.1813 0.2079 0.1971 0.2435 1.0000
I know there is the function corrcov() in matlab that finds the correlation matrix... So I tried,
corrcov(sigma_a)
I compared the results and both corrcov(sigma_a) and rho produced the same correlation matrix.
However then I wanted to change all of the pairwise correlations by exactly +0.1. Which I did, with
rho_u = (rho + .1) - .1*eye(10);
And I got the following correlation matrix...
1.0000 0.3365 0.4388 0.4396 0.5050 0.4772 0.4897 0.4899 0.4686 0.2556
0.3365 1.0000 0.3812 0.4656 0.3437 0.4274 0.4658 0.3631 0.4377 0.2638
0.4388 0.3812 1.0000 0.5027 0.5141 0.4792 0.5199 0.5133 0.5382 0.2985
0.4396 0.4656 0.5027 1.0000 0.4809 0.5638 0.7221 0.5246 0.5728 0.3295
0.5050 0.3437 0.5141 0.4809 1.0000 0.4681 0.5366 0.5732 0.5068 0.2948
0.4772 0.4274 0.4792 0.5638 0.4681 1.0000 0.6093 0.6499 0.5707 0.2813
0.4897 0.4658 0.5199 0.7221 0.5366 0.6093 1.0000 0.5797 0.6428 0.3079
0.4899 0.3631 0.5133 0.5246 0.5732 0.6499 0.5797 1.0000 0.5936 0.2971
0.4686 0.4377 0.5382 0.5728 0.5068 0.5707 0.6428 0.5936 1.0000 0.3435
0.2556 0.2638 0.2985 0.3295 0.2948 0.2813 0.3079 0.2971 0.3435 1.0000
However, when I attempt to take the adjusted correlation matrix and make it a co-variance matrix the cov() is not producing the right matrix. I tried...
b = cov(rho_u);
Why is that? Is there another way to do that? Or is there a way to adjust what I did with
rho = inv(sqrt(diag(diag(sigma_a))))*sigma_a*inv(sqrt(diag(diag(sigma_a))));
so that it does the opposite (rho found the correlation matrix) to get the co-varience matrix instead?
Based on my understanding from the answer below, then the co-variance matrix for rho_u would be achieved by, doing...
sigma = sqrt(var(rho_u));
D = diag(sigma);
sigma_u = D*rho_u*D
Is this what was meant? I was little confused by which variables I should take the variance to. I thought that meant rho_u?
The MATLAB function cov is not defined to transform a correlation matrix to covariance matrix, as its documentation says
cov(X), if X is a vector, returns the variance. For matrices, where
each row is an observation, and each column a variable, cov(X) is the
covariance matrix.
So simply feeding the correlation matrix to cov() won't work. What you need to calculate the covariance matrix is the variance of your variables (which you can calculate from your data, but didn't post here)
So in your example using the 10x10 correlation matrix rho you posted and using some random numbers for the the standard deviations
sigma = rand(size(rho(:,1)));
D = diag(sigma); % Make the sigmas appear on the diagonal of an 10x10 matrix
(you have to insert the calculated values from your input data, of course). You can then calculate the covariance matrix by
S = D*rho*D

polyfit/polyval with log scale through scatter points in matlab

I have a scatter plot with both x and y axes in log scale in Matlab. How do I add a line of best fit on the log scale?
Thanks!
x = [0.0090 0.0000 0.0001 0.0000 0.0001 0.0000 0.0097 0.0016 0.0006 0.0000 0.0016 0.0013 0.0023];
y = [0.0085 0.0001 0.0013 0.0006 0.0005 0.0006 0.0018 0.0076 0.0015 0.0001 0.0039 0.0015 0.0024];
scatter(x,y)
set(gca,'YScale','log');
set(gca,'XScale','log');
hold on
p = polyfit(log(x),log(y),1);
f = polyval(p,x);
plot(x,f,'Color',[0.7500 0.7500 0.7500],'linewidth',2)
When searching for the best fit, you need to use the original data x and y and not their logs. The log scale serves only for representation of the result.
Before use the polyval you need to sort the x. It does not matter when using normal axes, but can look strange with log-axes, because of the wrong sequence.
Here is the plot:
The code:
x = [0.0090 0.0000 0.0001 0.0000 0.0001 0.0000 0.0097 0.0016 0.0006 0.0000 0.0016 0.0013 0.0023];
y = [0.0085 0.0001 0.0013 0.0006 0.0005 0.0006 0.0018 0.0076 0.0015 0.0001 0.0039 0.0015 0.0024];
scatter(x,y);
set(gca,'YScale','log');
set(gca,'XScale','log');
hold on;
x_sort = sort(x);
p = polyfit(x,y,1);
f = polyval(p,x_sort);
plot(x_sort,f,'Color',[0.7500 0.7500 0.7500],'linewidth',2);
Is it what you wanted?

MatLab: Create 3D Histogram from sampled data

I have sampled data in the interval [0,1] in an Array transitions=zeros(101,101) which I want to plot as a 3D-histogram. transitions is filled with data similar to the example data provided at the end of this thread.
The first columns refers to the first observed variable X, the second column to the second variable Y and the third column is the normalized frequency. I.e. for the first row: the observed normalized frequency of the variable pair (0,0) is 0.9459. The sum of the normalized frequencies for (0,Y)thus is 1.
I tried to make (sort of) a 3D histogram with the following code:
x_c = (transitions(:,1) * 100)+1;
y = (transitions(:,2) * 100)+1;
z = transitions(:,4);
%A = zeros(10,10);
A = zeros(max(x_c),max(y));
for i = 1:length(x_c)
try
if(z(i)>0)
A(int32(x_c(i)), int32(y(i))) = abs(log(z(i)));
else
% deal with exceptions regarding log(0)
A(int32(x_c(i)), int32(y(i))) = 0;
end
catch
disp('');
end
end
bar3(A);
However, since it is sampled data in a discrete space A the output looks like the plot below. This is somehow misleading as there are 'gaps' in the plot (z-value = 0 for coordinates where I have no sampled data). I rather would like to have the sampled data being assigned to their corresponding plots, thus resulting in a 'real' 3d histogram.
By the way, as a result of my 'hack' of creating A also the x-,y- and z-scale is not correct. The 3D histogram's axes (all three) should be in the interval of [0,1].
ans =
0 0 0.9459
0 0.0500 0.0256
0 0.1000 0.0098
0 0.1100 0.0004
0 0.1500 0.0055
0 0.1600 0.0002
0 0.2000 0.0034
0 0.2100 0.0001
0 0.2500 0.0024
0 0.2600 0.0001
0 0.3000 0.0018
0 0.3200 0.0000
0 0.3700 0.0000
0 0.4000 0.0010
0 0.4200 0.0000
0 0.4500 0.0007
0 0.5000 0.0007
0 0.5300 0.0000
0 0.5500 0.0005
0 0.6000 0.0005
0 0.6300 0.0000
0 0.7000 0.0002
0 0.7400 0
0 0.7500 0.0003
0 0.7900 0.0000
0 0.8000 0.0002
0 0.8400 0.0000
0 0.8500 0.0002
0 0.8900 0.0000
0 0.9000 0.0002
0 0.9500 0.0001
0 1.0000 0.0001
0.0500 0 0.0235
0.0500 0.0500 0.0086
0.0500 0.1000 0.0045
. . .
. . .
. . .
. . .
. . .
0.9500 0.9000 0.0035
0.9500 0.9500 0.0066
0.9500 1.0000 0.0180
1.0000 0 0.0001
1.0000 0.0500 0.0001
1.0000 0.1000 0.0001
1.0000 0.1100 0.0000
1.0000 0.1500 0.0001
1.0000 0.1600 0.0000
1.0000 0.2000 0.0001
1.0000 0.2100 0.0000
1.0000 0.2500 0.0001
1.0000 0.2600 0.0000
1.0000 0.3000 0.0001
1.0000 0.3200 0.0000
1.0000 0.3700 0.0000
1.0000 0.4000 0.0002
1.0000 0.4200 0
1.0000 0.4500 0.0002
1.0000 0.5000 0.0003
1.0000 0.5300 0.0000
1.0000 0.5500 0.0004
1.0000 0.6000 0.0004
1.0000 0.6300 0.0000
1.0000 0.7000 0.0007
1.0000 0.7400 0.0000
1.0000 0.7500 0.0010
1.0000 0.7900 0.0000
1.0000 0.8000 0.0015
1.0000 0.8400 0.0001
1.0000 0.8500 0.0024
1.0000 0.8900 0.0002
1.0000 0.9000 0.0042
1.0000 0.9500 0.0111
1.0000 1.0000 0.3998
I found a solution by working on the non-aggregated data. In particular each row of the data set transitions contains one observation of Xand Y. I used the code below to produce a normalized 3D histogram (and a 2D map) as folllows:
function createHistogram(transitions)
uniqueValues = unique(transitions(:,1));
biases = cell(numel(uniqueValues),1);
for i = 1:numel(uniqueValues)
start = min(find(transitions(:,1) == uniqueValues(i)));
stop = max(find(transitions(:,1) == uniqueValues(i)));
biases(i) = mat2cell(transitions(start:stop,2));
end
combinedBiases = padcat(biases{1},biases{2},biases{3},biases{4},...
biases{5},biases{6},biases{7},biases{8},biases{9},biases{10},...
biases{11},biases{12},biases{13},biases{14},biases{15},biases{16},...
biases{17},biases{18},biases{19});
bins = 0:0.1:1;
[f, x] = hist(combinedBiases, bins);
%
% normalize
%
for i = 1:numel(f(1,:))
for j = 1:numel(f(:,i))
f(j,i) = f(j,i)/numel(biases{i});
end
end
bHandle = bar3(x, f);
ylim([-0.04,1.04])
for k = 1:length(bHandle)
zdata = get(bHandle(k),'ZData');
set(bHandle(k),'CData',zdata, 'FaceColor','interp');
end
colormap('autumn');
hcol = colorbar();
axis('square');
cpos=get(hcol,'Position');
cpos(4)=cpos(4)/3; % Halve the thickness
cpos(2)=0.4; % Move it down outside the plot#
cpos(1)=0.82;
set(hcol, 'Position',cpos);
xlabel('Enrollment biases');
ylabel('Aging biases');
zlabel('Bias transition probability');
title(strcat('Probability mass function of bias transitions (', device,')'));
set(gca,'XTick',0:2:20);
set(gca,'XTickLabel',0:0.1:1);
print('-dpng','-r600',strcat('tau_PMF3D_enrollment-ageing-', device));
view(2);
cpos(1)=0.84;
set(hcol, 'Position',cpos);
print('-dpng','-r600',strcat('tau_PMF2D_enrollment-ageing-', device));
end
From the comment on the question it appears you have the values you want to represent each bin count. If so an alternative solution is to plot using hist3 with "junk" data using correct x and y scales and then update the zdata of the surface object created with your bin data (modified to be in the correct format).
This modification to the bin data is fairly simple and consists of reshaping into a matrix then replicating and padding all the elements, the method is included in the code below.
Based on the ans variable at the end of the question, assuming
ans(:,1) gives x values
ans(:,2) gives y values
ans(:,3) gives the normalised bin counts
code
%// Inputs
zdata=ans(:,3); %// zdata=rand(21*21,1); % for testing
xvalues = 0:0.05:1;
yvalues = 0:0.05:1;
%// plot with junk data, [0,0] in this case
nx = numel(xvalues); ny = numel(yvalues);
bincenters = { xvalues , yvalues };
hist3([0,0],bincenters);
Hsurface = get(gca,'children');
%// apply bin count format
pad = [0 0 0 0 0;0 1 1 0 0;0 1 1 0 0;0 0 0 0 0;0 0 0 0 0]; %// padding for each point
ztrans=kron(reshape(zdata,[nx,ny]),pad); %// apply padding to each point
%// update plot
set(Hsurface,'ZData',ztrans)
%// to set colour based on bar height
colormap('autumn');
set(Hsurface,'CData',ztrans,'FaceColor','interp')
output

How to represent e^(-t^2) in MATLAB?

I am a beginner in MATLAB, and I need to represent e(-t2).
I know that, for example, to represent ex I use exp(x), and I have tried the following
1) tp=t^2; / tp=t*t;
x=exp(-tp);
2) x=exp(-t^2);
3) x=exp(-(t*t));
4) x=exp(-t)*exp(-t);
What is the correct way to do it?
If t is a matrix, you need to use the element-wise multiplication or exponentiation. Note the dot.
x = exp( -t.^2 )
or
x = exp( -t.*t )
All the 3 first ways are identical. You have make sure that if t is a matrix you add . before using multiplication or the power.
for matrix:
t= [1 2 3;2 3 4;3 4 5];
tp=t.*t;
x=exp(-(t.^2));
y=exp(-(t.*t));
z=exp(-(tp));
gives the results:
x =
0.3679 0.0183 0.0001
0.0183 0.0001 0.0000
0.0001 0.0000 0.0000
y =
0.3679 0.0183 0.0001
0.0183 0.0001 0.0000
0.0001 0.0000 0.0000
z=
0.3679 0.0183 0.0001
0.0183 0.0001 0.0000
0.0001 0.0000 0.0000
And using a scalar:
p=3;
pp=p^2;
x=exp(-(p^2));
y=exp(-(p*p));
z=exp(-pp);
gives the results:
x =
1.2341e-004
y =
1.2341e-004
z =
1.2341e-004