MATLAB循环遍历向量数组

时间:2017-01-26 22:03:02

标签: arrays matlab for-loop vector iteration

我无法弄清楚执行此操作的相应语法。我有4个向量,每个向量有15个元素。我想提取一个长度为4的向量,其中包含每个原始向量的第一个元素,然后用它做一些事情。然后我想用每个向量的第二个元素做同样的事情,并将所有答案存储在矩阵或数组中。像这样:

> The following error occurred converting from cell to double: Error
> using double Conversion to double from cell is not possible. Error in
> my_script (line 31)
>             new_vec(n)=fc(i);

但我明白了:

left = 0
right = len(alist)-1

mid = (left + right)//2

while left <= right:    #  loop through the list
    if alist[mid] < i :
        left = mid + 1
    elif alist[mid] > i :
        right = mid + 1
    elif alist[mid] == i :
        print ("word found at", blist.index(i) )    # will print the original index of element i.e. before sorting
        exit()     #to stop through infinite looping
    elif left > right:
        print ("Not Found!")       

我觉得有一种更简单的方法可以解决这个问题。

2 个答案:

答案 0 :(得分:1)

您的内循环正在循环1x4单元格:

let selectedIndexPath = NSIndexPath(forItem: 0, inSection: 0)
collectionView.selectItem(at: selectedIndexPath, animated: false, scrollPosition: .None)

这导致fc在每次迭代中都是1x1单元格。

要访问单元格内的实际数据,您需要使用大括号:

for fc = {vec_A, vec_B, vec_C, vec_D}
    new_vec(n)=fc{1}(i)
    n=n+1;
end

{1}将访问fc的第一个单元格和(i)所需的元素。

然而,使用像烧杯建议的矩阵更容易,更快:

for fc = {vec_A, vec_B, vec_C, vec_D}
    new_vec(n)=fc{1}(i)
    n=n+1;
end

答案 1 :(得分:0)

错误告诉fc(i)cell尝试将其作为double放入数组时返回for i = 1:15 new_cell=cell(4); n=1; for fc = {vec_A, vec_B, vec_C, vec_D} new_cell{n}=fc(i); n=n+1; end Final_answers{i}=functionDoThings(new_cell); end 。显然,您无法将数组转换为单个元素。

因此,不应将其存储到数组中,而应将其存储到单元格中。

sliderValue

希望有所帮助!