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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by