How can I use a loop to input different arrays into the same equation so I do not have to repeat code?
2 次查看(过去 30 天)
显示 更早的评论
I am trying to multipy three different arrays by 3 but I do not want to simply multiply them each by three, so is there a way I can use a for or loop function to do the multiplication for me for all three arrays?
0 个评论
回答(2 个)
SHIVAM KUMAR
2020-12-15
Don't know why you want to use a loop for that .
for i=1:3
Arr[i,:]=Arr[i,:]*3; %That's only useful if you have a vector.
% For arrays its not much useful to do in a loop.
end
3 个评论
Stephen23
2020-12-15
"...but I want to know if there is a basic functions to multiplty them all by three at once."
If you really want to multiply them "at once" then simply put all of the data into one numeric array (which could be a 3D array) and perform one multiplication.
If you want to keep them as separate arrays then simply store them all in one cell array (which they should be anyway) and use a basic loop:
C = {[1,2,3,4],[5,6,7,8],[9,10,11,12]};
for k = 1:numel(C)
C{k}*3
end
Defining the arrays in lots of separate variables is a mistake that will force you into writing slow, complex, inefficient, obfuscated, buggy code that is hard to debug. Indexing is much simpler and much more efficient.
SHIVAM KUMAR
2020-12-15
You can make A as a vector
A=[[1 2 3 4];[5 6 7 8];[9 10 11 12]];
A=A*3;
To use A or B or C we can use
A(1,:) %To use as A
A(2,:)%can be used as B
A(3,:)%Will work like C
1 个评论
SHIVAM KUMAR
2020-12-15
This can multiply them all at once. Just you have to be a bit careful in use.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!