简体   繁体   中英

Matlab Replacing Loop with Range Expression

I have function called buildRay which returns a 1x4 matrix. I call it multiple times like so:

rays = zeros(numRays, 4);
for j = 1:numRays
    rays(j, :) = buildRay(particle, (j-1)*anglePart, rayLength);
end

If I try and replace the loop with:

rays(1:numRays, :) = buildRay(particle, ((1:numRays)-1).*anglePart, rayLength);

I get the following error

??? Subscripted assignment dimension mismatch.

and I don't understand why.

Could someone please tell me what I'm doing wrong?

Thanks.

As the error message state, your left and right expressions have different size. You cannot do it in MATLAB.

To avoid for-loop you can use ARRAYFUN function:

rays = arrayfun(@(x) buildRay(particle, ((x-1).*anglePart, rayLength), 1:numRays);

You need to change buildRays to accept a vector (or matrix) of input arguments and return a matrix sized appropriately (ie not always 1x4 - if the input vector is N elements, return an Nx4 matrix).

Right now, you're trying to assign a 1x4 vector into a numRays x 4 spot - hence the error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM