フィルターのクリア

Is there a shorter/smarter way to do this code

1 回表示 (過去 30 日間)
Itzik Ben Shabat
Itzik Ben Shabat 2012 年 11 月 7 日
Hi, I am trying to creat a matrix of all possible coordinates given 2 coordinate vectors. my code is attached below. I know there is a better way to do this. can anyone help?
n=8 %can be any number
Ycoord=[0.5:n-0.5];
Xcoord=[0.5:n-0.5];
for i=1:n
for j=1:n
handles.coordinates{i,j}={Xcoord(i),Ycoord(j)};
end
end
thanks

採用された回答

Jan
Jan 2012 年 11 月 7 日
編集済み: Jan 2012 年 11 月 7 日
No, there is no "better" way, as long as you want to store the data in a cell array. You could use mat2cell, but then the same loops are performed inside this function also. One small improvement is to omit the unnecessary square brackets around the vectors (MLint should mention this already):
Ycoord = 0.5:n-0.5;
Xcoord = 0.5:n-0.5;
If you could store the values in a numerical array, simplifications are possible:
nX = length(Xcoord);
nY = length(Ycoord);
handles.coordinates = cat(3, repmat(Ycoord, nX, 1), repmat(Xcoord', 1, nY));
Then an pair of coordinates is restored by:
C = squeeze(handles.coordinates(i, j, :));

その他の回答 (1 件)

Daniel Shub
Daniel Shub 2012 年 11 月 7 日
It depends what you mean by better. To me the best code is the the code that is easiest for me to maintain unless it is a time bottleneck. If the maintainable code makes my overall function take too long, then I look into optimizing.
For your code, I would preallocate handles.coordinates and probably save the data as doubles instead of a cell array. As for eliminating the loops, you can and you will see an improvement, but then the code might be less readable and harder to maintain for you. For n equal to 8 (or any number of that order of magnitude) efficiency doesn't really matter unless you are calling the code a lot.

カテゴリ

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