problem looping through arrays

1 次查看(过去 30 天)
user343423
user343423 2021-11-17
编辑: the cyclist 2021-11-17
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
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.

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by