How to clear existing array size? I am getting "Subscripted assignment dimension mismatch" Error.
古いコメントを表示
I have multiple binary files to read and trying to save the data into a cell. I tried reading data using the the code given below. But it shows error "Subscripted assignment dimension mismatch" after reading few files. I figured it is showing error due to different array size. So can you please tell me is there any way to clear arrays so that new array of different dimension can be saved in the cell.
2 件のコメント
Bob Thompson
2018 年 11 月 15 日
The best way I've found to do this is by clearing the entire variable using clear(variable). Alternatively, if you're looking to replace a cell value, just turn the value into a blank with {}.
Do NOT use eval for trivial code like this:
files = dir('*.txt');
for i=1:length(files)
eval(['load ' files(i).name ' -ascii']);
end
It is much neater, more efficient, and easier to debug if you just call the function directly:
S = dir('*.txt');
for k = 1:numel(S)
S(k).data = load(S(k).name,'-ascii');
end
回答 (1 件)
clear is rarely needed in well written code. It is usually simpler and more efficient to just let MATLAB manage the memory by correctly defining/preallocating variables. In your code, the problem presumably happens on this line (you forgot to give us the complete error message, so I had to guess where the error occurs):
X(:,k)= fread(fid,1,'float');
where you use indexing to allocate values to X, but X was not defined anywhere earlier in the code (so it can grow, but never shrink... ouch!). The simple soluiton is to preallocate X with its final size before the loops: you already know how many loop iterations there will be, so try something like this (not working, just to get you started):
X = nan(1,a(4)); % preallocate!
for k=1:a(4)
X(:,k)= fread(fid,1,'float'); %%reading data and saving in X
end
The correct solution depends on the size/s of the data returned by fscanf, which you did not tell us anything about. In any case, it will be more efficient than calling clear before each loop.
To be honest that code does not look very efficient: by the time you get to fread you have four nested loops. The file you are importing seems to be a text file, so why not just use one of the inbuilt file-importing tools? If you upload your file we can help you with this.
カテゴリ
ヘルプ センター および File Exchange で MATLAB についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!