Reputation: 25
I've an array of zeros which is defined like this:
a=zeros(1,N)
Now,in a for loop,i need to have jth element of this array to be 1,and n-1 other elemnts to be zero,how should i do that? thanks.
Upvotes: 0
Views: 120
Reputation: 21
The simplest would be to use
a(1,j)=1
which will only change the jth element to 1. If you want to reassign 0 to other members of a, if it was changed before, you can then use
a(1,1:j-1)=0
a(1,j+1:length(a))
to set all non jth terms of a to 0.
If you provided us with clearer description of what you want to use a for, we may be able to help you better :)
Upvotes: 1
Reputation: 112679
One possibilty:
for jj = 1:N
a = [zeros(1,jj-1) 1 zeros(1,N-jj)];
%// do stuff
end
Another approach:
for a = eye(N)
a = a.';
%'// do stuff
end
Upvotes: 1