how can i make this loop?

hi friends im new in matlab could you please help me in this problem.
I have an equations A ; A=x*a-b
x=[1 2 5 8 10];
i want to put x values into equation A one by one to solve it, which i mean x1=1, to solve A1 and x2=2 to solve A2 and so on.
after that i want to use the results that i found in this equation B= (A1...An / c).
thanks

Answers (1)

No loop needed.
If you want to calculate ‘A’ with ‘a’ and ‘b’ already defined numerically as scalars, or if ‘b’ is a vector the same size as ‘x’, just do this:
A = x*a-b
If ‘a’ is a vector with the same dimensions as ‘x’, use element-wise multiplication:
A = x.*a+b
You might need to use bsxfun to do the vector multiplications if you have R2016a or earlier.

6 Comments

thanks for your answer Star Strider but i have to say that, if the equation is like this;
A(1,i)=x*a(i,1)
if i=1:20
x=[1 2 5 8 10]
i have to put x=1 to get 20 A, then put x=2 to get another 20 A and x=5 to get another 20 A and so on.
after that i have to put my A results in this equation B= (A1...An / c)
I have no idea what ‘a’ is.
Is it a vector or a matrix?
its a 20x1 matrix
Then ‘A’ is a (20x5) matrix:
a = rand(20,1);
x=[1 2 5 8 10];
b = rand;
A = a*x - b;
If you have a MATLAB version (release) earlier than R2016b, calculate ‘A’ as:
A = bsxfun(@times, x, a) -b;
to get the same result.
sad to say i use the old version R2013a :(
The bsxfun function was introduced in R2007a, so you can use it to do the multiplications. I believe the additions always used explicit expansion. If they do not, use bsxfun for those as well:
A = bsxfun(@minus, bsxfun(@times, x, a), b)
That should work.
The loops are all still there, however they are hidden in the bsxfun calls.

This question is closed.

Asked:

on 19 Jan 2020

Closed:

on 20 Aug 2021

Community Treasure Hunt

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

Start Hunting!