MATLAB Answers

put a function inside loop and save as matrix and csv

7 views (last 30 days)
joms on 25 Jul 2018
Commented: Shaula Garibbo on 23 Oct 2019
I have the following main script that pass value to a function. I would like to import different csv using function within a loop and output as summarize all data as matrix to be printed in an xls file . Here are my progress code so far, please help in matrix creationa and xls print. Thanks
%%main script-reads diff csv
clear all
Here is the function code
%%function to calculate output of main m
function [Result1,maxa]=csvimport(fileName)

Accepted Answer

Stephen on 25 Jul 2018
Edited: Stephen on 25 Jul 2018
Simpler and much more efficient than ugly dynamic variable names:
S = dir('Bus_Data*.csv');
N = numel(S);
R = cell(1,N);
M = cell(1,N);
for k = 1:N
km = csvread(S(k).name);
[R{k},M{k}] = csvimport(km);
If you want the files loaded in numeric order then download my FEX submission natsortfiles.
Shaula Garibbo
Shaula Garibbo on 23 Oct 2019
Thank you. I'll try a different approach as per your suggestion. (I know 'filepath' isn't valid, it's just that the filepath is ridiculously long so I thought I'd delete it to make the comment shorter - sorry, should have said).

Sign in to comment.

More Answers (1)

Krithika A
Krithika A on 25 Jul 2018
d = dir('Bus_Data*.csv'); % dir struct of all pertinent .csv files
n = length(d); % how many there were
for i = 1:n
data = csvread(d(i).name);
[Result1,maxa] = csvimport(data)
Eval isn't exactly efficient, but it's OK with you want the files separate.
Stephen on 26 Jul 2018
"My point is that beginners make mistakes because they are beginners"
In reality all programmers make mistakes! Beginners make mistakes, experienced developers make mistakes, I make mistakes, you make mistakes, we all make mistakes. It is precisely because everyone makes mistakes that programmers have developed tools to help find mistakes in code, and to help fix them. These tools includes static code checking, which checks code in the MATLAB editor, before it is even run. These tools complete function names, show inputs and help, find syntax errors and suggest fixes for them:
But sadly some beginners like to use tools like eval, which mean that none of those code checking tools work. Those beginners force themselves into writing more complex code (the risk of bugs increases with code complexity) and at the same time they remove lots of useful tools that would actually help them to find and fix those bugs. This is one reason why experienced MATLAB users avoid eval, and instead write simpler, neater, less buggy, and easier-to-fix code. Your answer increases the risk of bugs and makes debugging harder: it is not clear to me how this is supposed to help those beginners who make mistakes (as you point out).

Sign in to comment.


Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by