Manroop Singh
Manroop Singh

Reputation: 11

I am trying to incremen matrix power from 1:1:n in for loop in matlab but getting error "input must be scalar and square matrix"

I am tring to increment power of A matrix in for loop but getting error "input must be a scalar or square matrix"

function [S] =  myst()

st_1 =[0.1490 0 0.1723 0.1786 0.2015 0.1387 0.1600]';

for A = [0.5  0 0 0 0 0.5 0.2;0 0 0 0 0 0 0 ; 0 0 0 0.4 0.4 0 0;0 0 1 0.2 0.2 0 0;0 0 0 0.4 0.2 0 0.4;0 0 0 0 0 0.5 0;0.5 0 0 0 0.2 0 0.4]

    for n = 1:1:77
    A_n = A^n; % this A matrix is changing its index after every loop,
    %i don't know why index of A_n is changing?
    S = (A_n)*st_1;
    if S(1,1) == st_1(1,1)
    disp(n);
    break
    end
  end
end

disp(A);

end

Upvotes: 0

Views: 48

Answers (1)

Daniel
Daniel

Reputation: 36710

When writing a for loop like for A=[1,2,3;4,5,6;7,8,9],disp(A);end you are iterating the individual column of A. Just remove the outer for loop when you intend to process the full matrix:

function [S] =  myst()

st_1 =[0.1490 0 0.1723 0.1786 0.2015 0.1387 0.1600]';

A = [0.5  0 0 0 0 0.5 0.2;0 0 0 0 0 0 0 ; 0 0 0 0.4 0.4 0 0;0 0 1 0.2 0.2 0 0;0 0 0 0.4 0.2 0 0.4;0 0 0 0 0 0.5 0;0.5 0 0 0 0.2 0 0.4]

for n = 1:1:77
    A_n = A^n; % this A matrix is changing its index after every loop,
    %i don't know why index of A_n is changing?
    S = (A_n)*st_1;
    if S(1,1) == st_1(1,1)
        disp(n);
        break
    end
end

disp(A);

end

Upvotes: 1

Related Questions