0

I need to run a specific function 4 times, each time passing new arguments to it (getting them from array) and save the result in another array after each iteration.

Here is my function:

function VD (x,y,z)
(2*x*y*z)/1000

Here are my arrays with values:

x = [1,2,3]
y = [4,5,6]
z = [7,8,9]

Here is where I'm getting a mistake:

for i=1:4
result{i} = VD(x(i),y(i),z(i));
end

Mistake - Subscript indices must either be real positive integers or logicals.

I'd like to have array result with 4 values, where each value is a result of VD function return.

Hope it's clear.

Thank you.

2 Answers 2

1

You can avoid using the loop altogether:

x = [1,2,3]
y = [4,5,6]
z = [7,8,9]

result = 2 * x .* y .* z ./ 1000;
Sign up to request clarification or add additional context in comments.

1 Comment

Without the '.', the '' will perform a matrix multiplication. Try the following to see what I mean: A=rand(4); B=rand(4); AB, A.*B
1

Your function does not have a return value. It merely prints the results to the screen. Replacing your function definition with something like

function r = VD(x,y,z)
r = (2*x*y*z)/1000;

may help. However, there are much more efficient ways to do this particular task - see Gordon's answer on how to vectorize.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.