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
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.
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!