Search All of the Math Forum:
Views expressed in these public forums are not endorsed by
NCTM or The Math Forum.


dpb
Posts:
9,242
Registered:
6/7/07


Re: correct syntax for matlab..
Posted:
May 12, 2013 9:43 AM


On 5/12/2013 1:38 AM, virat rehani wrote: > counter=1; > eligible=[10,2]; > for i=1:M > for j=1:M > if (dis2(i,j)==1) row=i; > col=j; > eligible(counter,1)=row; > eligible(counter,2)=col; > counter=counter+1; > end > end > end
I'm not so sure you did find what you're actually looking for altho you haven't said clearly what the expected output is...let's look at what you have
counter=1; eligible=[10,2]; % this isn't what you want it to be I'm sure...
eligible here will simply be the vector 10,2 and will be overwritten the first pass thru the following loop that satisfies the if
Probably what you were looking for is
eligible=zeros(10,2);
But the question is why 10?
for i=1:M % what's M???
Since the loops are running over the array dis2, on can assume size(dis2)=[10,10] or larger or the loop would have failed on an address out of bounds error. If so, then there are up to 100 possible results from the if() tests if the content were full of 1's and the above attempt at allocation would be way short. Only if you know there can be no more than a total of 10 1's present would the allocation above be sufficient.
for j=1:M if (dis2(i,j)==1) eligible(counter,1)=i; eligible(counter,2)=j; counter=counter+1; end end end
The above will increment the counter and store the location of the i,j indices in the next row of the eligible array and have length equal to the number of 1's found in dis2.
That's precisely what
[eligible(:,1) eligible(:,2)]=find(dis2==1);
will do. The only difference is that your loops traverse the array in row order where as find operates in column order. If you need the specific order then
eligible=sortrows(eligible);
Only difference between this posting/solution is that in previous I assumed the array was either 0/1 so didn't use the '==1' in the argument of FIND; if that's the case it is superfluous but if the data could be something nonzero but not 1 then it is needed.
And, of course, the ordering of the resultant vector wasn't considered significant before.
Here's at the command line example...
>> x=rand(5); >> x(x>.6)=1;x(x<1)=0; % make up a set of data >> x x = 0 1 1 1 0 0 0 0 1 0 1 0 0 0 0 1 0 0 1 1 0 1 1 1 0 Your solution... >> k=1;for i=1:5,for j=1:5,if x(i,j)==1,e(k,:)=[i j];k=k+1;end,end,end
The "Matlab way"...(or one of the ways, anyway)... >> [e1(:,1) e1(:,2)]=find(x==1); >> e1=sortrows(e1);
>> all(all(e==e1)) ans = 1 >>
Shows oneforone consonance of each element in e and e1...




