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.

回答 (1 件)

the cyclist
the cyclist 2021 年 11 月 17 日
編集済み: the cyclist 2021 年 11 月 17 日

0 投票

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.

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2021 年 11 月 17 日

編集済み:

2021 年 11 月 17 日

Community Treasure Hunt

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

Start Hunting!

Translated by