need help vectorizing a complicated loop

조회 수: 2 (최근 30일)
supernoob
supernoob 2018년 12월 17일
편집: Stephen23 2018년 12월 19일
Hi,
I need to evaluate a vector of a function on a mesh then sum that vector at each point on the mesh. Let me elaborate:
I have a mesh:
a = -0.5:0.001:0.5;
b = a;
[A,B]=meshgrid(a,b);
At each point on that mesh, I want to evaluate a function over a vector (here, instead of giving the vector values I'm just trying to indicate that I have some vectors with some length):
% I have 3 vectors of length 2000 with some data in them
s = 2000x1 double, c = 2000x1 double, y = 2000x1 double
%at each point A,B on grid evaluate:
fake_function_vec = (c.*A+s.*B-y).^2
%result is some vector of length 2000. Now sum that vector
fake_function = sen(fake_function_vec,1)
%repeat for every other point on the mesh
I can't figure out how to do this efficiently. I'm currently using two for loops to evaluate the function (which returns a vector) and summing that vector at each point in the grid. Surely there must be a better way!
  댓글 수: 1
supernoob
supernoob 2018년 12월 17일
Another option is to use one for loop to evaluate each matrix element on the mesh then sum the stacked matrices. This is also slow.

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
Stephen23 2018년 12월 17일
편집: Stephen23 2018년 12월 19일
If you change the size of the s, c and y vectors to 1x1x2000 then this is easy. For MATLAB version R2016b or later:
s = rand(1,1,2000);
c = rand(1,1,2000);
y = rand(1,1,2000);
M = sum((c.*A+s.*B-y).^2,3)
For MATLAB versions prior to R2016b use bsxfun to replace the arithmetic operators.
  댓글 수: 1
supernoob
supernoob 2018년 12월 19일
Thanks so much! Unfortunately this took it from 30s per evaluation to 70s, which really surprised me.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

제품


릴리스

R2017b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by