I want to loop an equation over multiple rows
54 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
John D'Errico
2021-8-15
编辑:John D'Errico
2021-8-15
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.
更多回答(1 个)
Image Analyst
2021-8-15
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 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!