How can I use a loop to input different arrays into the same equation so I do not have to repeat code?
2 views (last 30 days)
Show older comments
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 Comments
Answers (2)
SHIVAM KUMAR
on 15 Dec 2020
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 Comments
Stephen23
on 15 Dec 2020
"...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
on 15 Dec 2020
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 Comment
SHIVAM KUMAR
on 15 Dec 2020
This can multiply them all at once. Just you have to be a bit careful in use.
See Also
Categories
Find more on Loops and Conditional Statements 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!