motaha
motaha

Reputation: 403

for looping with an incremented counter in matlab

I have a 15*15 binary matrix I multiply each row by its transpose to get another matrix from the outer product and then OR these matrices together to get a final matrix. I am trying to do this using a for loop since I have 15 rows and I might increase it to have a large number of rows, so, it is non-sense to do it manually. For the row by transpose multiplication I am following rayryeng answer. Yet, i want to apply to to the whole matrix. So, I am using the following code.

VectMat=randi([0 1],15,15);
resultt=zeros(15,15)
for i= 1:15
    row{i}=VecMat(1,:);
    result{i} = bsxfun(@times, row{i}.', row{i});
    resultt=result|resultt
end

I am getting an error and I know that the use of '{ }' isn't correct but if i tried using '[ ]' matlab will consider 'resultt' as an array and will keep adding to it in that manner. My pseudo code is, in the first iteration the 'i' will be one and all of the variables containing '{i}' will be variable number 1 then in the next iteration 'i' will be 2 and so on. So, can I do this on matlab?

Upvotes: 1

Views: 89

Answers (3)

knedlsepp
knedlsepp

Reputation: 6084

Let the linear algebra do the work for you:

VectMat = double(VectMat);
out = (VectMat.'*VectMat)~=0

This will be faster than using loops or bsxfun. Mind that matrix multiplication is not defined for logicals in MATLAB, so you might need to convert to double before, depending on how you create your 'binary' matrix. (In the example you provide, VectMat is already a double.)

Upvotes: 2

Lazarus
Lazarus

Reputation: 358

The answer using the any(bsxfun...) implementation is much more elegant (and I learned something new with that). However, with regards to your implementation, this is how you would make it work. Use

for i = 1:15
  row(i, :) = VecMat(i, :);
  result = bsxfun(@times, row(i, :).', row(i, :));
  resultt = result|resultt;
end

You can also replace row(i, :) with simply row.

Upvotes: 0

Divakar
Divakar

Reputation: 221684

You can use permute to create singleton dimensions needed by bsxfun to let the singleton-expansion do its work and which would essentially replace your loop. Here's the implementation -

any(bsxfun(@and,permute(VectMat,[3 2 1]),permute(VectMat,[2 3 1])),3)

Please note that one can use bsxfun@times in place of bsxfun(@and, but from my experience of working with bsxfun, using logical operators (@and in this case) could be more efficient.

Upvotes: 4

Related Questions