【问题标题】:Not sure what to do about error message "Conversion to double from cell is not possible."不确定如何处理错误消息“无法从单元格转换为双精度”。
【发布时间】:2021-02-22 21:51:52
【问题描述】:

我正在编写一个程序来查找矩阵 G 的索引,其中列索引或行索引只有一个 1,如果列索引和行索引都为 1,则删除任何找到的索引.然后我想获取这些索引并将它们用作数组 U 中的索引,这就是问题所在。索引似乎没有存储为整数,我不确定它们被存储为什么或为什么。我对 Matlab 很陌生(但这可能很明显),所以我不太了解类型如何为 Matlab 工作或它们是如何分配的。所以我不确定为什么我会收到标题中提到的错误消息,我不知道该怎么做。您能提供的任何帮助将不胜感激。

我之前忘了提这个,但是 G 是一个只包含 1 或 0 的矩阵,而 U 是一个字符串数组(我认为什么叫做单元格?)

function A = ISClinks(U, G)
B = [];
[rownum,colnum] = size(G);
j = 1;
for i=1:colnum
   s = sum(G(:,i));
   if s == 1
      B(j,:) = i;
      j = j + 1;
   end
end
for i=1:rownum
    s = sum(G(i,:));
    if s == 1
        if ismember(i, B)
            B(B == i) = [];
        else
            B(j,:) = i;
            j = j+1;
        end
    end
end
A = [];
for i=1:size(B,1)
    s = B(i,:);
    A(i,:) = U(s,:);
end
end

这是问题代码,但我不确定它有什么问题。

A = [];
for i=1:size(B,1)
    s = B(i,:);
    A(i,:) = U(s,:);
end

【问题讨论】:

  • 您能给我们提供一个典型输入参数(UG)的示例和预期输出吗?
  • 是的,抱歉,我刚刚进行了编辑以澄清这一点

标签: matlab


【解决方案1】:

您的程序的结构似乎是用 C 之类的语言编写的。在 MATLAB 中,在许多情况下,您通常可以用专用函数(例如 any() )替换低级循环。您的函数可以更有效地编写为:

function A = ISClinks(U, G)
  % Find columns and rows that are set in the input
  active_columns=any(G,1);
  active_rows=any(G,2).';

  % (Optional) Prevent columns and rows with same index from being simultaneously set
  %exclusive_active_columns = active_columns & ~active_rows; %not needed; this line is only for illustrative purposes
  %exclusive_active_rows = active_rows & ~active_columns; %same as above

  % Merge column state vector and row state vector by XORing them
  active_indices=xor(active_columns,active_rows);

  % Select appropriate rows of matrix U
  A=U(active_indices,:);
end

这个函数不会导致我测试的示例输入矩阵出错。如果U 是一个元胞数组(例如U={'Lorem','ipsum'; 'dolor','sit'; 'amet','consectetur'}),那么返回值A 也将是一个元胞数组。

【讨论】:

  • 我不知道这些较小的功能,但感谢您的提醒。我已经实现了这个,但问题是,我认为我之前没有很好地解释这一点,但它应该得到只有一个 1 的列或行,这就是我使用 sum 函数的原因,但我认为我可以弄清楚那部分。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-13
  • 1970-01-01
  • 2017-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多