在Matlab中加快循环 [英] Speed up for loop in Matlab

查看:175
本文介绍了在Matlab中加快循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于循环,我有以下,这使得我的程序在文件大小非常大时运行非常慢。



我从PLY文件中读取 data 作为这里使用命令 data = textread(fileName,'%s','delimiter ','\\\
');
data 是一个* 1单元格数组。 data 中的每个元素都是一个char值为7 * 1的单元数组。示例数据文件是此处



< (数据)-1
pc(i,1)=(str2double(cellstr(data {i,1}){1,1})pre> ));
pc(i,2)=(str2double(cellstr(data {i,1} {2,1})));
pc(i,3)=(str2double(cellstr(data {i,1} {3,1})));
pc(i,4)=(str2double(cellstr(data {i,1} {4,1})));
pc(i,5)=(str2double(cellstr(data {i,1} {5,1})));
pc(i,6)=(str2double(cellstr(data {i,1} {6,1})));
end


解决方案



 >> pc = str2double([data {:}]。')
pc =
0.1033 -0.2737 0.8570 221.0000 196.0000 174.0000 255.0000
0.1054 -0.2731 0.8550 220.0000 195.0000 173.0000 255.0000
...
0.1139 -0.2803 0.8490 221.0000 194.0000 172.0000 255.0000
0.1117 -0.2829 0.8500 225.0000 200.0000 178.0000 255.0000

您可以使用

 >>来移除最后一列和最后一行(就像您的问题中所做的那样) pc = pc(1:end-1,1:end-1)
pc =
0.1033 -0.2737 0.8570 221.0000 196.0000 174.0000
0.1054 -0.2731 0.8550 220.0000 195.0000 173.0000
.. 。
0.1139 -0.2803 0.8490 221.0000 194.0000 172.0000


I have the following for loop which makes my program runs very slow when the file size is very big. What is the best way to vectorize it.

I read data from a PLY file as here using the command, data = textread(fileName, '%s','delimiter', '\n');.data is a n*1 cell array. Each element in data is a 7*1 cell array of char values. Sample data file is here.

for i = 1:length(data)-1
    pc(i, 1) = (str2double(cellstr(data{i,1}{1,1})));
    pc(i, 2) = (str2double(cellstr(data{i,1}{2,1})));
    pc(i, 3) = (str2double(cellstr(data{i,1}{3,1})));
    pc(i, 4) = (str2double(cellstr(data{i,1}{4,1})));
    pc(i, 5) = (str2double(cellstr(data{i,1}{5,1})));
    pc(i, 6) = (str2double(cellstr(data{i,1}{6,1})));
end

解决方案

This will do what you want

>> pc = str2double([data{:}].')
pc =
    0.1033   -0.2737    0.8570  221.0000  196.0000  174.0000  255.0000
    0.1054   -0.2731    0.8550  220.0000  195.0000  173.0000  255.0000
    ...
    0.1139   -0.2803    0.8490  221.0000  194.0000  172.0000  255.0000
    0.1117   -0.2829    0.8500  225.0000  200.0000  178.0000  255.0000

You can remove the last column and row (as appears to be done in your question) with

>> pc = pc(1:end-1, 1:end-1)
pc =
    0.1033   -0.2737    0.8570  221.0000  196.0000  174.0000
    0.1054   -0.2731    0.8550  220.0000  195.0000  173.0000
    ...
    0.1139   -0.2803    0.8490  221.0000  194.0000  172.0000

这篇关于在Matlab中加快循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆