I want to loop an equation over multiple rows
40 views (last 30 days)
Show older comments
I know how to do this in excel but not in Matlab.
I have a huge matrix and in that I want to create a equation for only three column( a,b and c) s, but on every row. I want it to add a column with the answers to the equation(x).
The equation is x=a*b^c
In each row of columns a b and c the integers are different, so I can't use a simple number instead.
I am thinking the answer to this is a for loop but I am a begginer at Matlab so may be wrong.
In excel the way i would do this is create the equation in the top row and drag down,if that makes sense.
0 Comments
Accepted Answer
John D'Errico
on 15 Aug 2021
Edited: John D'Errico
on 15 Aug 2021
Your problem is you want to write this as if you are still using Excel. MATLAB is not a spreadsheet, but you are still thinking as if "YOU WANT TO USE A SPREADSHEET".
You have a matrix, with columns in it. The columns in a matrix do not have lettered names. So, first, I'll create a matrix with three columns.
M = randi(5,10,3)
So here I have a 10x3 matrix. 10 rows, 3 columns. Each element is an integer from 1 to 5 (in this case.)
Now you want to form something from these rows. How do you access a column of a matrix? Use indexing. So the first column (that which you want to call a) is just M(:,1). So all of the rows of M, but only the first column.
result = M(:,1).*M(:,2).^M(:,3);
You will see I used those dotted operators, .* and .^ to do the computations. That is because I have three vectors of elements, and you wish to do the same computation for each member of those sets of vector elements.
I would strongly recommend that you put the result of that computation into a new variable, not append it to your array. Learn to use named variables. Again, you are still thinking as if you are using a spreadsheet when you decide to append the result as a new column of the array.
Or, you can solve this using a simple loop.
Nrows = size(M,1); % how many rows in M?
result = zeros(Nrows,1); % preallocate result
for ind = 1:Nrows % Looping over each row
result(ind) = M(ind,1)*M(ind,2)^M(ind,3); % compute ONE result for each row
end
In either case, we will have for the array here:
result
Let the spreadsheet thinking go.
More Answers (1)
Image Analyst
on 15 Aug 2021
Try this;
columnsToProcess = [4, 9, 17]; % Whatever....
[rows, columns] = size(x); % Size of original matrix.
for col = columnsToProcess % Process only these particlar columns.
for row = 1 : rows
% Get the a, b, and c parameters.
% These vary on a row-by-row basis.
a = however you get it.
b = however you get it.
c = however you get it.
x(row, col) = a * b ^ c;
end
end
0 Comments
See Also
Categories
Find more on Spreadsheets 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!