Use a ready p-file to operate on matrices
2 views (last 30 days)
Show older comments
I have 345 matrices(S). So, I have from S1 to S345. I have a ready pfile function that operates on S. I want to make a loop to make that function work on each matrix seperately and give me 345 answers.
Lets say the pfile function is called Areas. So, I want to make something like this:
i = 1:345
Area = Areas(S(i))
end
to get the Area of each matrix from S1 to S345.
And to create the 345 matrices I used the following code(which is not mine).
S = ones(1,345);
tfile = tempdir + "assign_S.m";
fid = fopen(tfile, 'w');
for K = 1 : 345
fprintf(fid, 'S%d = S; S%d(1,%d) = 2;\n', K, K, K);
end
fclose(fid);
run(tfile)
1 Comment
Stephen23
on 5 Dec 2021
"So, I have from S1 to S345."
And that is the start of your difficulties.
Using numbered variables is a sign that you are doing something wrong. Read this to know why:
Accepted Answer
Stephen23
on 5 Dec 2021
Edited: Stephen23
on 5 Dec 2021
Your approach is complex, obfuscated, and inefficient.
Using numbered variables is a sign that you are doing something wrong. Read this to know why:
The MATLAB approach is to use simple and efficient indexing, for example using a cell array:
N = 345;
C = cell(1,N)
for k = 1:N
S = ones(1,N);
S(k) = k;
C{k} = Areas(S);
end
Because your data are all row vectors you could also do something similar with a simple numeric matrix:
4 Comments
Stephen23
on 5 Dec 2021
Edited: Stephen23
on 5 Dec 2021
"I get Unrecognized function or variable 'A'. I guess you wanted to write something else there?"
Yes, that was a spelling error: the line should be:
V = S;
"As I said before. I want to make 345 matrices of S...."
And that is what my code does: did you look inside the cell array yet?
Using indexing is how MATLAB works. If you want to use MATLAB, then you need to learn how to use indexing. You should do the Introductory Tutorials here, which teach very basic MATLAB concepts like how to access data in a loop using indexing:
More Answers (0)
See Also
Categories
Find more on Matrix Indexing 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!