gpt4 book ai didi

c++ - Matlab vs C++找到等于的Matrix的第一个元素

转载 作者:行者123 更新时间:2023-12-02 10:08:01 24 4
gpt4 key购买 nike

为什么此算法在Matlab中不起作用,而在C++中却起作用?


int a[3][4] = {
{0, 1, 1, 1} , /* initializers for row indexed by 0 */
{1, 0, 0, 0} , /* initializers for row indexed by 1 */
{0, 0, 0, 1} /* initializers for row indexed by 2 */
};

int x,y;
for(int i=1;i<3;i++)
for(int j=1;j<4;j++)
{
if (a[i][j]==1) // if element is equal to 1, get his position and stop.
{
x=i-1;
y=j-1;
break;
}
}
cout<<x<<" "<<y; // 1 2


如果我想在Matlab中做这样的事情,输出是不一样的(甚至不接近)。实际上,它根本不起作用。

Matlab代码:
for i=1:m
for j=1:n
if(a(i,j)==1)
k=i-1;
l=j-1;
break;
end
end
end


我该怎么办?

最佳答案

并不是说break被忽略了,它只是跳出了内循环,而只是在外循环中继续。恐怕没有“两次破门”的指示或类似的东西。一种解决方案是让一个标志在外循环中也中断:

int x, y;
bool stop = false;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
if (a[i][j] == 1) // if element is equal to 1, get his position and stop.
{
x = i - 1;
y = j - 1;
stop = true;
break;
}
}
if (stop)
break;
}

这是极少数情况下的一种,您可以放置​​ goto来减少麻烦:
int x, y;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
if (a[i][j] == 1) // if element is equal to 1, get his position and stop.
{
x = i - 1;
y = j - 1;
goto finishNestedLoop; // used as a "break twice"
}
}
}
finishNestedLoop:;

其他解决方案包括将嵌套循环放入其自己的函数中,并改为使用 return:
#include <iostream>
#include <tuple>
std::tuple<int, int> getXY() {
int a[3][4] = {
{0, 1, 1, 1} , /* initializers for row indexed by 0 */
{1, 0, 0, 0} , /* initializers for row indexed by 1 */
{0, 0, 0, 1} /* initializers for row indexed by 2 */
};
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
if (a[i][j] == 1) // if element is equal to 1, get his position and stop.
return std::tuple<int, int>{i-1, j-1};
}
}
}

int main() {
auto[x, y] = getXY();
std::cout << x << " " << y;
}

另外,您确定有关 i - 1吗?要从0索引到1索引,您需要 i + 1

关于c++ - Matlab vs C++找到等于的Matrix的第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59209281/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com