problem looping through arrays

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.

Réponses (1)

the cyclist
the cyclist le 17 Nov 2021
Modifié(e) : the cyclist le 17 Nov 2021

0 votes

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.

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by