How to repeat the same function for different matrix ?

Hello,
I have many vectors with different row sizes and I would like to repeat the same function for them.
Example:
A1 = [8; 9; 10]
A2 = [1; 2]
B1 = [0.1; 0.3; 0.6]
B2 = [0.5; 0.9]
P1 = A1 .* B1
P2 = A2 .* B2
...
How could I do to solve that?
Thanks in advance,

댓글 수: 5

samw function? which function ?
Sorry, I was not clear.
Actually I want to calculate
the vector P
P = A * B
But I want to do that for many vectors A (A1, A2, A3, ...) and vectors B(B1, B2, B3, ...)
I think that I need to created a function, but I do not know how.
Read about function:
doc function % to know more about creating a function
Luna
Luna 2019년 3월 20일
편집: Luna 2019년 3월 20일
Do you want to get each P for each A and B seperately? or the P will be a long vector?
Also your vectors in your workspace or defined in a variable? Simply you can do this:
vectorA = [A1;A2; .. bla bla .. An];
vectorB = [B1;B2; .. bla bla .. Bn];
vectorP = vectorA .* vectorB;
Stephen23
Stephen23 2019년 3월 20일
편집: Stephen23 2019년 3월 20일
"But I want to do that for many vectors A (A1, A2, A3, ...) and vectors B(B1, B2, B3, ...)"
Numbered variables are a sign that you are doing something wrong.
Dynamically accessing badly named variables is one way that beginners force themselves into writing slow, complex, obfuscated, buggy code that is hard to debug. Read this to know why:
"How to repeat the same function for different matrix ?"
This is trivial using idnexing.
Indexing is simple, neat, compact, easy to debug, and very efficient (unlike what you are trying to do). You should use indexing, just like experienced MATLAB users do.

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

답변 (1개)

YUNUS AKSOY
YUNUS AKSOY 2019년 3월 20일
for c=1:2;
eval(['P',num2str(c),'=A',num2str(c),'.*B',num2str(c),';']);
end

댓글 수: 3

madhan ravi
madhan ravi 2019년 3월 20일
편집: madhan ravi 2019년 3월 20일
Yet another eval() user.
Stephen23
Stephen23 2019년 3월 20일
편집: Stephen23 2019년 3월 20일
Note that the MATLAB documentation specifically recommends avoiding doing this:
Dynamically accessing badly named variables is one way that beginners force themselves into writing slow, complex, obfuscated, buggy code that is hard to debug. Read this to know why:
Indexing is simple, neat, compact, easy to debug, and very efficient (unlike what you recommend). Experienced MATLAB users recommend indexing, you can too.
Thank you all for your help and explanations. I am a beginner in MATLAB and yours comments have helped me a lot !!

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

카테고리

질문:

2019년 3월 20일

댓글:

2019년 3월 20일

Community Treasure Hunt

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

Start Hunting!

Translated by