Paulinchen2
Paulinchen2

Reputation: 125

Replacing For Loops in Matlab

I am trying to replace for loops in Matlab.

 function A=ansatz(s,p,n)
 si(1:n+1)=2*((1:n+1)-1)/n-1;

 A(1,:)= s';
 for j=1:n+1
     for i=1:n+1
         A(j,i)=s(j)-si(i);
     end
 end

 A=ansatz([-1,-0.9,-0.7,0.6,1],2,4)

What i am trying to do is to fill the Matrix A with

s(1)-si(1)   s(1)-si(2)  ... s(1)-si(n+1)
s(2)-si(1)   s(2)-si(2)  ... s(2)-si(n+1)


s(n+1)-si(1)   s(n+1)-si(2)  ... s(n+1)-si(n+1)

Basicly the last two loops have to be replaced with vector iterations. All I accomplish is the first row.

A(1,:)= s(1)-si(1:n+1);

Anyone has a hint on how to iterate properly? Edit: No for or while loops can be used.

Upvotes: 0

Views: 324

Answers (1)

Shai
Shai

Reputation: 114786

If I understand correctly you need

s = bsxfun(@minus, s(:), si(:).' )

If a loop must be used

for ii=1:numel(s)
    A(ii,:) = s(ii) - si(1:n+1);
end

No bsxfun and no loops (hands tied behind back, one eye shut, 3 books and a fork balanced over my head):

s = repmat( s(:), [1 n+1] ) - repmat( si(:).', [n+1 1] );

Upvotes: 4

Related Questions