比较矩阵matlab 2

发布于 2024-12-18 01:51:43 字数 617 浏览 2 评论 0原文

这是我关于比​​较两个矩阵的第二个问题。我尝试比较两个矩阵,(3x3) 和 (4x6)。下面的代码工作完美,但如果我想用注释行替换矩阵 z,matlab 不再喜欢我的代码:( 你能告诉我我的错误吗! 我会很感激, 米高梅

clear
x=[0  4  8 ;3 2 5 ;2 1 5 ]';
y=[0 1.1 2 2.1 3.6 7.3;1 3 2.2 2 3 2.4 ;2 1 3.3 3.4 6.7 5.8;3 3.4 5 6.6 6.5 7.8]';
z=zeros(6,3);
for i=1:3
    for j=1:3
        for p=1:6
            for r=1:4
                if x(i,1)==y(p,1)
                    z(p,j)=x(i,j);
                elseif (x(i,1)<y(p,1))&&(y(p,1)<x(i+1,1))
            z(p,j)=(x(i,j)+x(i+1,j))./2;%(x(i,j)+x(i+1,j)+x(i,j+1)+x(i+1,j+1))./4
        end
    end
        end
    end
end

结束

this is my second question about comparing two matrices.I tried to compare two matrixes, (3x3) and (4x6).Fallowing code works perfect, but if I want to replace matrix z with commented line,matlab doesn't like my code anymore:( Could you please show my mistake!
I will be greatfull,
mgm

clear
x=[0  4  8 ;3 2 5 ;2 1 5 ]';
y=[0 1.1 2 2.1 3.6 7.3;1 3 2.2 2 3 2.4 ;2 1 3.3 3.4 6.7 5.8;3 3.4 5 6.6 6.5 7.8]';
z=zeros(6,3);
for i=1:3
    for j=1:3
        for p=1:6
            for r=1:4
                if x(i,1)==y(p,1)
                    z(p,j)=x(i,j);
                elseif (x(i,1)<y(p,1))&&(y(p,1)<x(i+1,1))
            z(p,j)=(x(i,j)+x(i+1,j))./2;%(x(i,j)+x(i+1,j)+x(i,j+1)+x(i+1,j+1))./4
        end
    end
        end
    end
end

end

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

若相惜即相离 2024-12-25 01:51:43

您发布的代码并不完美 - 您只是幸运地选择了您选择的数字组合;)。

只需比较您发布的 elseif 语句中的值,您就会发现该代码无法按预期工作。

将此行切换

elseif (x(i,1)<y(p,1))&&(y(p,1)<x(i+1,1))

为:

elseif ((y(p,1)<x(i+1,1)&&x(i,1)<y(p,1)))

这是因为 matlab 计算语句中的第一个表达式,如果它为 false,则不会检查第二个语句 - 因此,自代码中的第一个语句以来,您不会收到错误最后一个元素为假 8 < 7.3

您收到的错误是,因为您尝试访问矩阵索引之外的元素。

您有一个 3x3 矩阵,并尝试在 for 循环的最后一次运行中访问元素 (4,1)。 y 矩阵也有同样的问题。

the code you posted does NOT work perfect - you got just lucky with the combination of numbers you have choosen ;).

Just witch the comparison of the values in the elseif statement you posted and you will see that this code does not work as intended.

switch this line:

elseif (x(i,1)<y(p,1))&&(y(p,1)<x(i+1,1))

to:

elseif ((y(p,1)<x(i+1,1)&&x(i,1)<y(p,1)))

This is, because matlab evaluetes the first expression in the statement and if it is false, it doesn't check the second statement - Therefore you don't get an error since the first statemaent in your code for the last elements is false 8 < 7.3

The error you are getting is, because you try to access elements out of the index of the matrices.

You have a 3x3 matrix and try to acces the element (4,1) in the last run of your for-loop. The same problem with the y matrix.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文