【问题标题】:MATLAB nested for loop to read variables to insert in equationMATLAB嵌套for循环以读取要插入方程的变量
【发布时间】:2015-04-09 09:51:22
【问题描述】:

我在 Matlab 工作区中有变量,它由图像的非零像素坐标组成。

从存储的变量中,我想逐列读取以定义 x1、x2、y1、y2 值,以便我可以应用于我的方程。

例如在第一个循环中:

x1=127, y1=38
x2=128, y2=38

第二个循环(步长为 1):

x1=128, y1=38
x2=129, y2=38

这些是我想到的代码,但我知道它不会工作。

%r is for the row values, and c is for the column values.%
coordinates = [r, c];

%To define the size of my coordinates%
num_rows = size(coordinates,1);
num_cols = size(coordinates,2);

%To calculate the slopes using row-column values%
for x1 = 1:num_rows
    for y1 = 1:num_cols
        for x2 = 2:num_rows
            for y2 = 2:num_cols

                  %Calculate M%
                  M = (y2-y1)/(x2-x1);
                end
            end
        end
    end

如何使用嵌套的 for 循环定义值 x1,x2,y1,y2?这样我就可以在我的方程中使用我的 x1,x2,y1,y2 斜率 = (y2-y1)/(x2-x1)。

【问题讨论】:

  • 我有点迷路了,那些二维数组在哪里/哪些是?
  • 从你的问题中不清楚你想问什么。请描述并提供更多信息。
  • @Divakar 抱歉,我在使用编程术语方面还是新手。它不是数组,它是我收集并存储在我的工作区中的变量。我编辑问题并包含一张图片。希望它足够清楚。 TQ
  • @articuno 我已经编辑并包含了一张图片。在使用编程术语方面还是新手,我弄错了。 TQ
  • 矩阵coordinates的列数可以大于2吗?

标签: arrays matlab for-loop


【解决方案1】:

据我了解,您的 coordinates 矩阵将只有 2 列,其中第 1 列代表 x 坐标,第 2 列代表对应的 y 坐标。在这种情况下,您可以简单地找到斜率矩阵 -

coordinates = [r, c];
num_rows = size(coordinates,1);
shiftedCoordinates = coordinates(2:num_rows,:);
diffMat = shiftedCoordinates-coordinates(1:num_rows-1,:);
slopeMat = diffMat(:,2)./diffMat(:,1);

slopeMat 是你想要的矩阵 (M)

【讨论】:

  • 我已经尝试过您的代码并且它有效。它比使用我自己丢失的 for 循环要简单得多。谢谢,这解决了我的问题。
猜你喜欢
  • 2013-12-06
  • 1970-01-01
  • 1970-01-01
  • 2018-12-25
  • 1970-01-01
  • 2014-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多