Repeating the same statement using loop - matlab

This is the same statement for 3 times. how to do this with loop. Here, the matrix G1 dimension is 3*10. so in each part i am taking different column.
G2 = f_range_m(1:8:length(timeline_ms),:); %%%% measured range
G1 = OrgiRange(1:8:end,:);
M1 = G1(:,1);
dist11 = abs(bsxfun( #minus,G2,M1));
[~,col1] = min(dist11,[],2);
Result_1 = diag(G2(:,col1));
M2 = G1(:, 2);
dist22 = abs(bsxfun(#minus,G2, M2));
[~,col2] = min(dist22,[],2);
Result_2 = diag(G2(:,col2));
M3 = G1(:, 3);
dist33 = abs(bsxfun(#minus,G2, M3));
[~,col3] = min(dist33,[],2);
Result_3 = diag(G2(:,col3));
I am trying this way. However not getting desired output. Result dimension should be 13*3.
obj = 3;
for ix = 1:obj
M = G1(:,ix);
dist = abs(bsxfun(#minus,G2,M));
[~,col] = min (dist,[],2);
Result = diag(G2(:,col));
end

With your updated code you nearly solved it. Everything which remains is writing to the columns of Result instead of overwriting it in each iteration.
obj = 3;
Result=nan(size(G1,1),obj);
for ix = 1:obj
M = G1(:,ix);
dist = abs(bsxfun(#minus,G2,M));
[~,col] = min (dist,[],2);
Result(:,ix) = diag(G2(:,col));
end

Related

Swapping fragments of matrices Matlab

I wrote a program implementing Gaussian Elimination with Complete Pivoting:
function x = gecp(A,b)
x = b;
n = length(A);
p = 1:n;
l = b;
for k = 1:n
[i,j] = find(A(k:n,k:n)==max(abs(A(k:n,k:n)),[],'all'));
i = i+k-1;
j = j+k-1;
[A(k,:),A(i,:)] = deal(A(i,:),A(k,:));
[A(:,j),A(:,k)] = deal(A(:,k),A(:,j));
[b(i),b(k)] = deal(b(k),b(i));
[p(k),p(j)] = deal(p(j),p(k));
temp = (k+1):n;
l(temp) = A(temp,k)/A(k,k);
b(temp) = b(temp)-l(temp).*b(k);
A(temp,temp) = A(temp,temp)-l(temp).*A(k,temp);
end
x(n) = b(n)/A(n,n);
for k = (n-1):-1:1
s = 0;
for h = (k+1):n
s = s+A(k,h)*x(h);
end
x(k) = (b(k)-s)/A(k,k);
end
x(p) = x;
And it is called like this:
N = 5; A = randn(N); b = randn(N,1); x = gecp(A,b)
Unfortunately all lines containing deal function (used for swapping rows of columns of matrices), give me following (or similar) error: "Unable to perform assignment because the size of the left side is 1-by-5 and the size of the right side is 0-by-5."
Unfortunately I have no idead why would the width of these vectors be changed to 0 as I wrote excatly the same thing on both sides.

How to loop through the columns of a Matlab table by using the headings?

I am trying to make a for-loop for the Matlab code below. I have named each column with JAN90, FEB90, etc. all the way up to AUG19, which can be found in a matrix named "data". At this point I need to change the month and year manually to obtain the result I want. Is there a way to iterate over the columns by the column name? Would it be easier to name the columns Var1, Var2 etc.?
clear;
clc;
data = readtable('Data.xlsx','ReadVariableNames',false);
data(1,:) = [];
data.Var2 = str2double(data.Var2);
data.Var3 = str2double(data.Var3);
data.Var4 = str2double(data.Var4);
data.Var5 = str2double(data.Var5);
data.Var6 = str2double(data.Var6);
data.Var7 = str2double(data.Var7);
data.Var8 = str2double(data.Var8);
data.Var9 = str2double(data.Var9);
data.Var10 = str2double(data.Var10);
data.Var11 = str2double(data.Var11);
data.Var12 = str2double(data.Var12);
data.Var13 = str2double(data.Var13);
data(:,1) = [];
data = table2array(data);
data = array2table(data.');
data = table2cell(data)
data = cell2table(data, 'VariableNames',{'JAN90','FEB90','MAR90','APR90','MAY90','JUN90','JUL90','AUG90'...
,'SEP90','OCT90','NOV90','DEC90','JAN91','FEB91','MAR91','APR91','MAY91','JUN91','JUL91','AUG91'...
,'SEP91','OCT91','NOV91','DEC91','JAN92','FEB92','MAR92','APR92','MAY92','JUN92','JUL92','AUG92'...
,'SEP92','OCT92','NOV92','DEC92','JAN93','FEB93','MAR93','APR93','MAY93','JUN93','JUL93','AUG93'...
,'SEP93','OCT93','NOV93','DEC93','JAN94','FEB94','MAR94','APR94','MAY94','JUN94','JUL94','AUG94'...
,'SEP94','OCT94','NOV94','DEC94','JAN95','FEB95','MAR95','APR95','MAY95','JUN95','JUL95','AUG95'...
,'SEP95','OCT95','NOV95','DEC95','JAN96','FEB96','MAR96','APR96','MAY96','JUN96','JUL96','AUG96'...
,'SEP96','OCT96','NOV96','DEC96','JAN97','FEB97','MAR97','APR97','MAY97','JUN97','JUL97','AUG97'...
,'SEP97','OCT97','NOV97','DEC97','JAN98','FEB98','MAR98','APR98','MAY98','JUN98','JUL98','AUG98'...
,'SEP98','OCT98','NOV98','DEC98','JAN99','FEB99','MAR99','APR99','MAY99','JUN99','JUL99','AUG99'...
,'SEP99','OCT99','NOV99','DEC99','JAN00','FEB00','MAR00','APR00','MAY00','JUN00','JUL00','AUG00'...
,'SEP00','OCT00','NOV00','DEC00','JAN01','FEB01','MAR01','APR01','MAY01','JUN01','JUL01','AUG01'...
,'SEP01','OCT01','NOV01','DEC01','JAN02','FEB02','MAR02','APR02','MAY02','JUN02','JUL02','AUG02'...
,'SEP02','OCT02','NOV02','DEC02','JAN03','FEB03','MAR03','APR03','MAY03','JUN03','JUL03','AUG03'...
,'SEP03','OCT03','NOV03','DEC03','JAN04','FEB04','MAR04','APR04','MAY04','JUN04','JUL04','AUG04'...
,'SEP04','OCT04','NOV04','DEC04','JAN05','FEB05','MAR05','APR05','MAY05','JUN05','JUL05','AUG05'...
,'SEP05','OCT05','NOV05','DEC05','JAN06','FEB06','MAR06','APR06','MAY06','JUN06','JUL06','AUG06'...
,'SEP06','OCT06','NOV06','DEC06','JAN07','FEB07','MAR07','APR07','MAY07','JUN07','JUL07','AUG07'...
,'SEP07','OCT07','NOV07','DEC07','JAN08','FEB08','MAR08','APR08','MAY08','JUN08','JUL08','AUG08'...
,'SEP08','OCT08','NOV08','DEC08','JAN09','FEB09','MAR09','APR09','MAY09','JUN09','JUL09','AUG09'...
,'SEP09','OCT09','NOV09','DEC09','JAN10','FEB10','MAR10','APR10','MAY10','JUN10','JUL10','AUG10'...
,'SEP10','OCT10','NOV10','DEC10','JAN11','FEB11','MAR11','APR11','MAY11','JUN11','JUL11','AUG11'...
,'SEP11','OCT11','NOV11','DEC11','JAN12','FEB12','MAR12','APR12','MAY12','JUN12','JUL12','AUG12'...
,'SEP12','OCT12','NOV12','DEC12','JAN13','FEB13','MAR13','APR13','MAY13','JUN13','JUL13','AUG13'...
,'SEP13','OCT13','NOV13','DEC13','JAN14','FEB14','MAR14','APR14','MAY14','JUN14','JUL14','AUG14'...
,'SEP14','OCT14','NOV14','DEC14','JAN15','FEB15','MAR15','APR15','MAY15','JUN15','JUL15','AUG15'...
,'SEP15','OCT15','NOV15','DEC15','JAN16','FEB16','MAR16','APR16','MAY16','JUN16','JUL16','AUG16'...
,'SEP16','OCT16','NOV16','DEC16','JAN17','FEB17','MAR17','APR17','MAY17','JUN17','JUL17','AUG17'...
,'SEP17','OCT17','NOV17','DEC17','JAN18','FEB18','MAR18','APR18','MAY18','JUN18','JUL18','AUG18'...
,'SEP18','OCT18','NOV18','DEC18','JAN19','FEB19','MAR19','APR19','MAY19','JUN19','JUL19','AUG19'});
m = [1 2 3 6 12 24 36 60 84 120 240 360]';
for i=1:100
t = i;
data.X_1 = (1-exp(-m./t))./(m./t);
data.X_2 = ((1-exp(-m./t))./(m./t))-exp(-m./t);
model_1 = fitlm(data, 'FEB95 ~ X_1 + X_2');
RSS(100,:) = zeros ;
res = model_1.Residuals.Raw;
res(any(isnan(res), 2), :) = [];
RSS(i) = sum(res.^2);
end
RSS(:,2) = [1:1:100];
min = min(RSS(:,1));
t = find(RSS(:,1) == min)
data.X_1 = (1-exp(-m./t))./(m./t);
data.X_2 = ((1-exp(-m./t))./(m./t))-exp(-m./t);
model_1 = fitlm(data, 'FEB95 ~ X_1 + X_2')
res = model_1.Residuals.Raw;
res(any(isnan(res), 2), :) = [];
RSS = sum(res.^2)
intercept = model_1.Coefficients.Estimate(1,1);
beta_1 = model_1.Coefficients.Estimate(2,1);
beta_2 = model_1.Coefficients.Estimate(3,1);
Yhat = intercept + beta_1.*data.X_1 + beta_2.*data.X_2;
plot(m, Yhat)
hold on
scatter(m, data.FEB95)
I.e "FEB95" should be dynamic? Any suggestions?
Her is how I would approach your problem. First realize that VarNames=data.Properties.VariableNames will get a list of all column names in the table. You could then loop over this list. For example
for v=VarNames
current_column = v{1};
% ....
% Define the model spec for the current column
model_spec = [current_column ' ~ X_1 + X_2'];
% and create the model
model_1 = fitlm(data, model_spec);
% ... Continue computation ... and collect results in a table or array
end

Error: In assignment A(I) = B, the number of elements in B and I must be the same

I'm stuck on K2 as it brought up this error:
In an assignment A(I) = B, the number of elements in B and
I must be the same.
I ran the debugger and I found out that J4 alone was a vector while other variables were all scalar.
How can I resolve this error to have the plot?
Here is the code that I ran.
h1 = 1*10^-6;
h2 = (10:10:1500)*10^-6;
a = 62.5*10^-6;
b = a+h1;
c = b+h2;
alpha_1 = 0.55*10^-6;
alpha_2 = 17.2*10^-6;
alpha_3 = 14.2*10^-6;
zeta = 6.3*10^-6;
P11 = 0.121;
P12 = 0.27;
neff = 1.456;
U1 = 0.17;
U2 = 0.32;
U3 = 0.31;
E1 = 0.74*10^11;
E2 = 1.08*10^11;
E3 = 1.96*10^11;
n = 1;
while(n<=150)
J1(n) = E2*(b^2-a^2)*(1-U1)-E1*a^2*(1-U2)-E1*b^2*(1+U2);
J2(n) = 2*E1*b^2;
J3(n) = E1*E2*(b^2-a^2)*(alpha_2 - alpha_1);
J4(n) = 2*E3*(c(n)^2-b^2)*a^2;
J5(n) = E2*(b^2-a^2)*(1-U3)*b^2+E2*(b^2-a^2)*(1+U3)*c(n)^2-E3*(c(n)^2-b^2)*(1+U2)*a^2-E3*(c(n)^2-b^2)*(1-U2)*b^2;
J6(n) = E2*E3*(c(n)^2 - b^2)*(b^2-a^2)*(alpha_2-alpha_3);
K1(n) = ((alpha_3-alpha_1)*E3*(c(n)^2-b^2)+(alpha_2-alpha_1)*E2*(b^2-a^2))/(E1*a^2+E2*(b^2-a^2)+E3*(c(n)^2-b^2));
K2(n) = (J2*J6-J3*J5)/(J2*J4-J1*J5);
Sr(n) = (neff^2/2)*(P11+P12)*(((1-U1)*K2/E1)-U1*K1);
Sz(n) = (1+P12)*(K1-(2*U2*K2/E1));
St(n) = alpha_1+zeta;
Km(n) = St+Sz+Sr;
n=n+1;
end
plot(h2,Km)
To recap what was already said in one answer, here's how I would modify the code:
h1 = 1e-6;
h2 = (10:10:1500)*1e-6;
a = 62.5*1e-6;
b = a+h1;
c = b+h2;
alpha_1 = 0.55*1e-6;
alpha_2 = 17.2*1e-6;
alpha_3 = 14.2*1e-6;
zeta = 6.3*1e-6;
P11 = 0.121;
P12 = 0.27;
neff = 1.456;
U1 = 0.17;
U2 = 0.32;
U3 = 0.31;
E1 = 0.74*1e11;
E2 = 1.08*1e11;
E3 = 1.96*1e11;
% pre-allocate variables
J1 = zeros(size(h2));
J2 = zeros(size(h2));
J3 = zeros(size(h2));
J4 = zeros(size(h2));
J5 = zeros(size(h2));
J6 = zeros(size(h2));
K1 = zeros(size(h2));
K2 = zeros(size(h2));
Sr = zeros(size(h2));
Sz = zeros(size(h2));
for n=1:length(h2)
J1(n) = E2*(b^2-a^2)*(1-U1)-E1*a^2*(1-U2)-E1*b^2*(1+U2);
J2(n) = 2*E1*b^2;
J3(n) = E1*E2*(b^2-a^2)*(alpha_2 - alpha_1);
J4(n) = 2*E3*(c(n)^2-b^2)*a^2;
J5(n) = E2*(b^2-a^2)*(1-U3)*b^2+E2*(b^2-a^2)*(1+U3)*c(n)^2-E3*(c(n)^2-b^2)*(1+U2)*a^2-E3*(c(n)^2-b^2)*(1-U2)*b^2;
J6(n) = E2*E3*(c(n)^2 - b^2)*(b^2-a^2)*(alpha_2-alpha_3);
K1(n) = ((alpha_3-alpha_1)*E3*(c(n)^2-b^2)+(alpha_2-alpha_1)*E2*(b^2-a^2))/(E1*a^2+E2*(b^2-a^2)+E3*(c(n)^2-b^2));
K2(n) = (J2(n)*J6(n)-J3(n)*J5(n))/(J2(n)*J4(n)-J1(n)*J5(n));
Sr(n) = (neff^2/2)*(P11+P12)*(((1-U1)*K2(n)/E1)-U1*K1(n));
Sz(n) = (1+P12)*(K1(n)-(2*U2*K2(n)/E1));
end
St = alpha_1+zeta;
Km = Sz+Sr+St;
plot(h2,Km)
Notes:
I have used a for loop to ensure the vector lengths are consistent with h2
I have pre-allocated the variables for speed
I have added various (n) to K1, K2, J1, J2, etc... in the equations to have only scalar operations
I have moved stuff out of the for loop that didn't need to be there
This gives the following plot (in Octave)
I ran your code and I found out that the dimensions of the vectors used to compute K2 are not compatible, e.g. each of J2 and J6 is a 1-row by 2-columns vector and you cannot multiply those. This also applies for the other multiplications. Depending on what you want to compute, you should transpose either one of them in each multiplication.
FYI: J.' is the transposed version of J in MATLAB.

Why do I get such a bad loss in my implementation of k-Nearest Neighbor?

I'm trying to implement k-NN in matlab. I have a matrix of 214 x's that have 9 columns of attributes with the 10th column being the label. I want to measure loss with a 0-1 function on 10 cross-validation tests. I have the following code:
function q3(file)
data = knnfile(file);
loss(data(:,1:9),'KFold',data(:,10))
losses = zeros(25,3);
new_data = data;
new_data(:,10) = [];
sdd = std(new_data);
meand = mean(new_data);
for s = 1:214
for q = 1:9
new_data(s,q) = (new_data(s,q) - meand(q)) / sdd(q);
end
end
new_data = [new_data data(:,10)];
for k = 1:25
loss1 = 0;
loss2 = 0;
for j = 0:9
index = floor(214/10)*j+1;
curd1 = data([1:index-1,index+21:end],:);
curd2 = new_data([1:index-1,index+21:end],:);
for l = 0:20
c1 = knn(curd1,k,data(index+l,:));
c2 = knn(curd2,k,new_data(index+l,:));
loss1 = loss1 + (c1 ~= data(index+l,10));
loss2 = loss2 + (c2 ~= new_data(index+l,10));
end
end
losses(k,1) = k;
losses(k,2) = 100*loss1/210;
losses(k,3) = 100*loss2/210;
end
function cluster = knn(Data,k,x)
distances = zeros(193,2);
for i = 1:size(Data,1)
row = Data(i,:);
d = norm(row(1:size(row,2)-1) - x(1:size(x,2)-1));
distances(i,:) = [d row(10)];
end
distances = sortrows(distances,1);
cluster = mode(distances(1:k,2));
I'm getting 40%+ loss with almost no correlation to k and I'm sure that something here is wrong but I'm not quite sure.
Any help would be appreciated!

Subscripted assignment dimension mismatch in matlab

I executed this code using Feature Matrix 517*11 and Label Matrix 517*1. But once the dimensions of matrices change the code cant be run. How can I fix this?
The error is:
Subscripted assignment dimension mismatch.
in this line :
edges(k,j) = quantlevels(a);
Here is my code:
function [features,weights] = MI(features,labels,Q)
if nargin <3
Q = 12;
end
edges = zeros(size(features,2),Q+1);
for k = 1:size(features,2)
minval = min(features(:,k));
maxval = max(features(:,k));
if minval==maxval
continue;
end
quantlevels = minval:(maxval-minval)/500:maxval;
N = histc(features(:,k),quantlevels);
totsamples = size(features,1);
N_cum = cumsum(N);
edges(k,1) = -Inf;
stepsize = totsamples/Q;
for j = 1:Q-1
a = find(N_cum > j.*stepsize,1);
edges(k,j) = quantlevels(a);
end
edges(k,j+2) = Inf;
end
S = zeros(size(features));
for k = 1:size(S,2)
S(:,k) = quantize(features(:,k),edges(k,:))+1;
end
I = zeros(size(features,2),1);
for k = 1:size(features,2)
I(k) = computeMI(S(:,k),labels,0);
end
[weights,features] = sort(I,'descend');
%% EOF
function [I,M,SP] = computeMI(seq1,seq2,lag)
if nargin <3
lag = 0;
end
if(length(seq1) ~= length(seq2))
error('Input sequences are of different length');
end
lambda1 = max(seq1);
symbol_count1 = zeros(lambda1,1);
for k = 1:lambda1
symbol_count1(k) = sum(seq1 == k);
end
symbol_prob1 = symbol_count1./sum(symbol_count1)+0.000001;
lambda2 = max(seq2);
symbol_count2 = zeros(lambda2,1);
for k = 1:lambda2
symbol_count2(k) = sum(seq2 == k);
end
symbol_prob2 = symbol_count2./sum(symbol_count2)+0.000001;
M = zeros(lambda1,lambda2);
if(lag > 0)
for k = 1:length(seq1)-lag
loc1 = seq1(k);
loc2 = seq2(k+lag);
M(loc1,loc2) = M(loc1,loc2)+1;
end
else
for k = abs(lag)+1:length(seq1)
loc1 = seq1(k);
loc2 = seq2(k+lag);
M(loc1,loc2) = M(loc1,loc2)+1;
end
end
SP = symbol_prob1*symbol_prob2';
M = M./sum(M(:))+0.000001;
I = sum(sum(M.*log2(M./SP)));
function y = quantize(x, q)
x = x(:);
nx = length(x);
nq = length(q);
y = sum(repmat(x,1,nq)>repmat(q,nx,1),2);
I've run the function several times without getting any error.
I've used as input for "seq1" and "seq2" arrays such as 1:10 and 11:20
Possible error might rise in the loops
for k = 1:lambda1
symbol_count1(k) = sum(seq1 == k);
end
if "seq1" and "seq2" are defined as matrices since sum will return an array while
symbol_count1(k)
is expected to be single value.
Another possible error might rise if seq1 and seq2 are not of type integer since they are used as indexes in
M(loc1,loc2) = M(loc1,loc2)+1;
Hope this helps.