Avoid overwriting of results in for loop

조회 수: 2 (최근 30일)
Turbulence Analysis
Turbulence Analysis 2020년 8월 19일
댓글: Stephen23 2022년 12월 14일
Hi,
I intend to save the results of function output defined inside the for loop, actually for each iteration output pushes 1 x 4 files, so, after the 10 iteration I suppose to get 10 x 4.. But somehow it overwrites, hence, I am getting only the value of last iteration.. Please help me resolve this...
output = zeros(10,4);
for f = 1:1:10
if (f>=1) && (f<=9)
fname_strt = 'B0000' ;
elseif (f>=10) && (f<=99)
fname_strt='B000';
elseif (f>=100) && (f<=999)
fname_strt='B00';
else
fname_strt='B0';
end
fname_end = num2str(f);
fname = strcat(fname_strt,fname_end,'.txt');
A=dlmread(fname,'\t',1,0);
sz = [112 98];
x = reshape(A (:,1),sz);
y = reshape(A (:,2),sz);
u = reshape(A (:,3),sz)';
v = reshape(A (:,4),sz)';
x1 = x(:,1);
y1 = y (1,:)';
output=IDvortex(x1,y1,u,v);
end
  댓글 수: 1
Stephen23
Stephen23 2022년 12월 14일
As an aside, you should replace all of that complex IF/ELSEIF/ELSE, NUM2STR, and STRCAT with this:
fname = sprintf('B%05d.vc7',j)

댓글을 달려면 로그인하십시오.

답변 (1개)

KSSV
KSSV 2020년 8월 19일
편집: KSSV 2020년 8월 19일
You canmake your output matrix a 3D.
clc; clear all ;
output = zeros(10,4,10);
for f = 1:1:10
if (f>=1) && (f<=9)
fname_strt = 'B0000' ;
elseif (f>=10) && (f<=99)
fname_strt='B000';
elseif (f>=100) && (f<=999)
fname_strt='B00';
else
fname_strt='B0';
end
fname_end = num2str(f);
fname = strcat(fname_strt,fname_end,'.txt');
A=dlmread(fname,'\t',1,0);
sz = [112 98];
x = reshape(A (:,1),sz);
y = reshape(A (:,2),sz);
u = reshape(A (:,3),sz)';
v = reshape(A (:,4),sz)';
x1 = x(:,1);
y1 = y (1,:)';
M = IDvortex(x1,y1,u,v);
output(:,:,f) = M ;
end
  댓글 수: 5
Turbulence Analysis
Turbulence Analysis 2020년 8월 19일
I thought below should work, but still it end with error
Unable to perform assignment because the left and right sides have a different number of elements.
output1 = zeros(10,4);
for f = 1:1:10
if (f>=1) && (f<=9)
fname_strt = 'B0000' ;
elseif (f>=10) && (f<=99)
fname_strt='B000';
elseif (f>=100) && (f<=999)
fname_strt='B00';
else
fname_strt='B0';
end
fname_end = num2str(f);
fname = strcat(fname_strt,fname_end,'.txt');
A=dlmread(fname,'\t',1,0);
sz = [112 98];
x = reshape(A (:,1),sz);
y = reshape(A (:,2),sz);
u = reshape(A (:,3),sz)';
v = reshape(A (:,4),sz)';
x1 = x(:,1);
y1 = y (1,:)';
output=IDvortex(x1,y1,u,v);
output1(f)= output;
% a= output(:,1);
% b=output(:,2);
% c=output(:,3);
% d=output(:,4);
% output1(f,:) = [a,b,c,d];
end
KSSV
KSSV 2020년 8월 19일
A = zeros(10,4,10) ;
for i = 1:10
A(:,:,i) = rand(10,4) ;
end
Above is giving any error? No, it will not.
You have to check the dimensions of M. Check it.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by