フィルターのクリア

Dimensional problem in for loop.

1 回表示 (過去 30 日間)
Xiaohan Du
Xiaohan Du 2017 年 11 月 8 日
コメント済み: Greg 2017 年 11 月 8 日
Hi all,
Imagine there is function which takes a matrix as input, perform some operations to each element, and gives an output of same dimension matrix. The dimension of the input matrix can be random. For example:
clear; clc;
% the 1d case.
inpt1d = [1 2 3]';
otpt1d = zeros(3, 1);
for i = 1:3
% the operation is square root.
otpt1d(i) = sqrt(inpt1d(i));
end
% the 2d case.
inpt2d = [1 2 3; 4 5 6; 7 8 9]';
otpt2d = zeros(3, 3);
for i = 1:3
for j = 1:3
otpt2d(i, j) = sqrt(inpt2d(i, j));
end
end
Here in the example I manually set i and j for 2d case. However if I want the input to suit any dimension, I cannot set the index manually any more. So for this kind of problem, if I'd like to deal with any dimensions with for loop, how should I do it?
Thanks!
  1 件のコメント
Greg
Greg 2017 年 11 月 8 日
編集済み: Greg 2017 年 11 月 8 日
MATLAB inherently understands linear-indexing, do some Google searching on those terms and you should learn you only ever need a single loop (with maybe a tiny bit of slick pre-allocation).

サインインしてコメントする。

採用された回答

KL
KL 2017 年 11 月 8 日
編集済み: KL 2017 年 11 月 8 日
EDITED
First you should make sure if loop is required at all in the first place, if yes then I would suggest linear indexing and reshape.
For example
A = rand(3,3,3);
B = A(:);
now it's just a column vector. you could use a single loop with numel(). and once you are done, you could reshape it like
C = reshape(B,size(A))
  3 件のコメント
KL
KL 2017 年 11 月 8 日
Ah yes, I totally misread it, thanks Greg.
Greg
Greg 2017 年 11 月 8 日
The "tiny bit of slick pre-allocation" I referred to in my comment to the original question negates the reshape:
A = rand(3,3,3);
B = 0.*A; % or B = NaN.*A;

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by