Matrix Dimension must agree - Vectorization

1 view (last 30 days)
Toan Nguyen
Toan Nguyen on 13 Jul 2020
Answered: Mahesh Taparia on 16 Jul 2020
Hi there,
I created a function called Fx which takes an single number as input and produce a 1 single number as output.
I tried to run:
n = 1:10;
r = Fx(n);
What I expected is an array of r 1x10, each contains the result of Fx of n from 1 to 10.
However, I got "Matrix dimensions must agree" instead. This does not make sense to me. I tried to run it with for loop and it worked just fine.
for n = 1:10
r(n) = Fxl(n);
end
The array involved in the calculation of Fx is 115824. So I tried with array n of 1x115824 then the code only return the result of n(1,1) only.
Does anyone know what's going on here?
If so, please let me know.
Thank you
  9 Comments
madhan ravi
madhan ravi on 13 Jul 2020
“I tried to run it with for loop and it worked just fine.”
What is the problem then??
Toan Nguyen
Toan Nguyen on 13 Jul 2020
I'm sorry that I did not clarify the objective.
For loop is slow with 100 runs already and my aim is around 100k.
From what I heard, vectorization is faster. Thus, that's what I'm trying to do

Sign in to comment.

Answers (1)

Mahesh Taparia
Mahesh Taparia on 16 Jul 2020
Hi
It seems you want to apply a function on each element of an array without applying for loop. In this case, create that function according to the input, i.e, give array as the function input and apply the whole computation on that array which finally returns a vector as functional output.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!