I have a matrix BB = [-1 5 6;4 -3 2;5 6 -7]. How can i print the location(index) of the positive elelments using for loop and using while loop ?

I have this matrix BB = [-1 5 6;4 -3 2;5 6 -7]. I want to know how can I display the location of the positive elements using for loop and using while loop

4 Comments

I am assuming this is a homework question as we did the while loop in the previous question.
For educational purposes, it would be good to see your attempt. What have you tried and what are you having trouble with?
I tried to do this for the for loop:
for BB = [-1 5 6;4 -3 2;5 6 -7]
i = [1:length(BB)]
if (BB(i) >= 0)
i
end
end
but it gave me :
i =
1 2 3
i =
1 2 3
i =
1 2 3
I didn't try for the while loop yet
That's not the correct syntax for a for loop. Check this documentation page: link
I tried to do this i=[1:length(BB)] for BB = [-1 5 6;4 -3 2;5 6 -7] if (BB(i) >= 0) i end end it gave me :i =
1 2 3
and I tried to do
BB = [-1 5 6;4 -3 2; 5 6 -7]
i = [1:length(BB)]
for (BB(i)>= 0)
i
end
it gave me :BB =
-1 5 6
4 -3 2
5 6 -7
i =
1 2 3
for (BB(i)>= 0)
Error: Invalid expression. When calling a function or
indexing a variable, use parentheses. Otherwise, check for
mismatched delimiters.

Sign in to comment.

 Accepted Answer

BB = [-1 5 6;4 -3 2;5 6 -7] ;
[nx,ny] = size(BB) ;
for i = 1:nx
for j = 1:ny
if BB(i,j)>0
fprintf('%d %d %f\n',i,j,BB(i,j))
end
end
end

3 Comments

it gave me this : 1 2 5.000000 1 3 6.000000 2 1 4.000000 2 3 2.000000 3 1 5.000000 3 2 6.000000
but can you give me a way by using while loop
Thank you very much the for loop code works, but I need another way by using the while loop
Thank you very much it works. I figured a way by using while loop

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Release

R2018a

Asked:

on 24 Jul 2018

Commented:

on 25 Jul 2018

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!