Clear Filters
Clear Filters

Saving Answers in For Loop in Matlab

2 views (last 30 days)
Nihar Jariwala
Nihar Jariwala on 13 Mar 2021
Answered: Walter Roberson on 13 Mar 2021
Hi Everyone,
I am running one code for all my files I am doing that in a for loop. However, I have a small question:
Question: Suppose I have 8 files in my directory, when I run the code in the foor loop I will get 8 different answers. I wan't to save all those 8 answers as a Matrix. Could someone help me with the same?
Thanks,
Nihar.
clc
clear all
close all
folder = dir('12LPS_G_Fr5.42_X=0_Y=*');
n = length(folder);
Y = [0;10;15;20;25;30;35;5];
for i=1:n;
load (folder(i).name);
LT = logical(voltageA>2.5);
%Converting Leading Tip to Binary
TT = logical(voltageB>2.5);
%Converting Trailing Tip to Binary
LT_C = mean(LT);
%Void Fraction Leading Tip
TT_C = mean(TT);
%Void Fraction Trailing Tip
z = [];
for i = 1:n
z = [z i+rand];
end

Answers (1)

Walter Roberson
Walter Roberson on 13 Mar 2021
folder = dir('12LPS_G_Fr5.42_X=0_Y=*');
n = length(folder);
Y = [0;10;15;20;25;30;35;5];
all_LT_C = cell(n, 1);
all_TT_C = cell(n, 1);
all_z = zeros(n,n);
for i=1:n
loaded = load(folder(i).name);
LT = logical(loaded.voltageA>2.5);
%Converting Leading Tip to Binary
TT = logical(loaded.voltageB>2.5);
%Converting Trailing Tip to Binary
LT_C = mean(LT);
%Void Fraction Leading Tip
TT_C = mean(TT);
%Void Fraction Trailing Tip
z = [];
for i = 1:n
z = [z i+rand];
end
all_LT_C{i} = LT_C;
all_TT_C{i} = TT_C;
all_z(i,:) = z;
end
I do not assume here that voltageA or voltageB are vectors, so I do not assume that taking the mean() will give a scalar, or that it will give the same size each time.
You really should be more careful on the mean, as it operates along the first non-singular dimension. If your voltageA was 3 x 1 one time it would give 1 x 1 (okay), and if it were 3 x 2 it would give 1 x 2 (okay), but if it were 1 x 3 then it would give 1 x 1 -- so you cannot predict the number of columns of the result just looking at the number of columns of the input.

Categories

Find more on Creating and Concatenating Matrices 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!