MATLAB: Hi every one , how can i do a for cycle with diffrent vector length , thank you

MATLABmatrix

clear all
clc
X=rand(17,1)
Y=rand(31,1)
Z=rand(28,1)
K=rand(31,1)
n=31
for i=1:n
A=[X(:,n) , Y(:,n) ,Z(:,n) ,K(:,n)];
AT{1,n}= inv(A{1,n}'*A{1,n})*A{1,n}';
end

Best Answer

  • You can put them in a cell array and let cell2mat handle the removal of empty elements. I have no clue what you want to do with that variable inside your loop, so I replaced it with sum to have a proof of principle. (also, no need for clear all)
    X=rand(17,1);
    Y=rand(31,1);
    Z=rand(28,1);
    K=rand(31,1);
    A=cell(numel(X),4);
    A(1:numel(X),1)=num2cell(X);
    A(1:numel(Y),2)=num2cell(Y);
    A(1:numel(Z),3)=num2cell(Z);
    A(1:numel(K),4)=num2cell(K);
    AT=zeros(1,size(A,1));
    for n=1:size(A,1)
    B=A(n,:);B=cell2mat(B);
    AT(n)= sum(B);
    end