problem looping through arrays

1 view (last 30 days)
user343423
user343423 on 17 Nov 2021
Edited: the cyclist on 17 Nov 2021
This is the question: Let M be a matrix of positive integers. Write a function with header [Q] =myTrigOddEven(M), where Q(i ,j ) = sin (M(i,j)) if M (i , j ) is even, and Q(i ,j ) =cos (M (i , j )) if M (i , j ) is odd.
This is the function I came up with:
function [Q] = myTrigOddEven(M)
for i = 1:(length(M)-1)
for j = 1:(length(M)-1)
if mod(Q(i,j),2) == 0
Q(i,j) = sin (M (i , j ));
else
Q(i,j) = cos (M (i , j ));
end
end
end
end
I'm getting an error with the statement in the if and the else. At the parts Q(i,j) = sin (M (i , j )); and Q(i,j) = cos (M (i , j ));, it says that Q changes size on every loop interation, and I'm not sure how to fix that.

Answers (1)

the cyclist
the cyclist on 17 Nov 2021
Edited: the cyclist on 17 Nov 2021
I think you intended
if mod(M(i,j),2) == 0
rather than
if mod(Q(i,j),2) == 0
Regarding the warning about Q changing size, you want to preallocate that array. For example, you could put
Q = zeros(size(M));
at the beginning of the function.
You can read about why preallocation is important in this documentation.

Categories

Find more on Creating and Concatenating Matrices 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!