construct a matrix in Matlab without using iterative functions

40 Views Asked by At

I have $r= \mbox{randi}(1000,100,1)$. I want to construct a matrix $A(i,j)$ with the following relation: \begin{cases} A(i,j)=1 & \mbox{if} r(i)=j \\ A(i,j)=0 & \mbox{otherwise} \end{cases} P.s: I should do it with some vector/matrix operations. I can use “ones” and “zeros” functions. I cannot use iterative functions such as “for”, “while”, … or any other specific functions.

1

There are 1 best solutions below

0
On BEST ANSWER

The following code should do what you aimed to describe:

r = randi(1000,100,1);

l = 1000.*[0:length(r)-1] + r';

A = zeros(1000,100);
A(l) = 1;
A = A';

spy(A)

% for comparison

B = zeros(1000,100);
for i = 1:length(r)
    B(s(i),r(i)) = 1;
end

spy(B)

I hope it helps.