首页 > 解决方案 > 将单个单元格中的值转换为矩阵

问题描述

我正在尝试创建一个小脚本,使用户能够从头开始创建一个新矩阵(10x8),稍后将用于双线性插值。

目前我这样做的方法是prompt在弹出块中使用 10 行的函数。然后,用户将为他们想要的每一行输入 8 个值。这将输出一个 10x1 的单元格,其中包含值。那么这个 10x1 的单元需要转换成一个 10x8 的矩阵

下面是我当前代码的简化示例(5x3)矩阵想法。

用户输入;

用户数据输入

输入数据后,我试图让 Matlab 将这些数字转换为,在这个例子中,一个 5x3 矩阵,例如

1 2 3

4 5 6

7 8 9

1 5 9

7 5 3

使用此代码

prompt = {'Enter the first row values','Enter the second row values','Enter the third row values'...
           'Enter the forth row values', 'Enter the fifth row values'}%, 'Entre the sixth row values'...
         %'Enter the seventh row values', 'Enter the eighth row values', 'Enter the nineth row values' ...
         %'Enter the tenth row values'};
     title = ' bi-linear interpolation grid ';
     dims = [1 50]; 

answer = inputdlg(prompt,title,dims); 

bi_linear_interpolation_grid = cell2mat(answer);

但是,这会产生 5x5?Char 中的值。下图

MATLAB 结果

我也尝试过使用str2double另一种以前在网上使用过的方法,但根本不起作用。

我知道这可能不是输入数据的最有效方法(我对 Matlab 还很陌生),但我发现这种方法是一种快速而干净的方法。如果您知道更简单的方法,请指出正确的方向

非常感谢您提供的任何帮助。

标签: matlab

解决方案


您正在寻找split()功能:

answer = {'1 2 3' ; '4 5 6' ; '7 8 9' ; '10 11 12' ; '13 14 15'};
answer = str2double(split(answer))

答案=

 1     2     3
 4     5     6
 7     8     9
10    11    12

至于更简单的数据输入方式,我喜欢直接从 Excel 复制粘贴到工作区的变量面板中。请记住,要从 Excel 粘贴到 Matlab,您应该使用 CTRL + SHIFT + V 而不是标准的 CTRL + V。


推荐阅读