Can variables used in defining a for-loop or an if-loop be used in the code block contained in said loops?
Show older comments
I'm working on a problem that requires me to perform an operation, either sin() or cos(), based on whether or not an element in a 2-Dimensional matrix, M, is even or odd. The output should be an array, Q, whose elements are the results of each element in M as they go through the operations.
I've gotten as far as setting up for-loops and an if structure to analyze each element in M and to act accordingly, but when I run the program the end result is an array containing nothing but zeros. What's odd is that the last element in M is always correctly put through the loop structures, but only the last element, no matter what size M is.
function [Q] = myTrigOddEven(M)
% function [Q] = myTrigOddEven(M)
Q = zeros(size(M));
[i,j] = size(M);
for rows = 1:i %for loop includes the rows of M
for cols = 1:j %for loop includes the cols of M
if rem(M(i,j),2) == 0 %if M(i,j) is even
Q(i,j) = sin(M(i,j));
else
Q(i,j) = cos(M(i,j));
end %end if statement
end %end for statement (cols)
end %end for statement (rows)
end %end function myTrigOddEven
Example Output (Using above function):
>> A
A =
1 2 3 4 5 6 7 8 9 10
1 3 5 7 9 11 13 15 17 19
>> Q = myTrigOddEven(A)
Q =
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0.9887
>> cos(19)
ans =
0.9887
I'd greatly appreciate some help. Assignment is due soon, hehe.
Answers (1)
Better Solution:
Rather than doing this using slow and bulky loops, why not learn how to use MATLAB effectively by writing fast and efficient vectorized code:
function Q = myTrigOddEven(M)
idx = 1==mod(M,2);
Q(idx) = cos(M(idx));
Q(~idx) = sin(M(~idx));
end
This solution is much more efficient that using two for-loops.
Your Code
The problem in your code is this: you are not using the loop variables rows and cols inside the loops, bu8t instead you are using i and j, which do not change inside the loops. Thus the indexing never changes, and the index only ever refers to the last element of the arrays.
[R,C] = size(M);
for r = 1:R
for c = 1:C
if rem(M(r,c),2) == 0
Q(r,c) = sin(M(r,c));
else
Q(r,c) = cos(M(r,c));
end
end
end
1 Comment
Nathaniel Abrenilla
on 23 Sep 2015
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!