フィルターのクリア

if function in cell arrays

2 ビュー (過去 30 日間)
gsourop
gsourop 2016 年 11 月 19 日
コメント済み: the cyclist 2016 年 11 月 19 日
Hi everyone,
I try to use to use the if function in cell arrays. If I have A that is 2x100 cells and each cell contains a 6x1 vector. I need to set the following constraint:
for k=1:2
for t=1:100
if A{k,t}(:,1)<-1;
A{k,t}(:,1)=-1;
elseif A{k,t}(:,1)>2;
a{k,t}(:,1)=2;
end;
end;
end;
This code does not deliver an error. However, it doesn't do what I aim at. It should go on each cell and check the each value of the vectors have a value over or lower than the if statements.
Thanks in advance

回答 (1 件)

the cyclist
the cyclist 2016 年 11 月 19 日
編集済み: the cyclist 2016 年 11 月 19 日
There are a couple issues with your code. The main issue is that the line
A{k,t}(:,1)<-1
will have a vector output, and therefore the if statement is not doing what you expect. (It would have to be true for every value in the vector, to trigger the if.)
A more straightforward way to do this is as follows:
for k=1:2
for t=1:100
A{k,t} = max(A{k,t},-1);
A{k,t} = min(A{k,t}, 2);
end
end
which compares each element of the vector to the threshold value, and replaces it if necessary.
This same operation can be done very compactly, eliminating the for loops completely, with the cellfun function instead:
A = cellfun(@(x)max(x,-1),A,'UniformOutput',false);
A = cellfun(@(x)min(x, 2),A,'UniformOutput',false);
You can even collapse this into a one-liner:
A = cellfun(@(x)min(2,max(x,-1)),A,'UniformOutput',false);
but what you are doing starts to get a little "obfuscated".
(The for loop seems to be the faster method, though, in the limited testing I did.)
  2 件のコメント
gsourop
gsourop 2016 年 11 月 19 日
Thanks a lot! I've started working on cell arrays to create a more compact and fast way for the first steps of my code, but then it has started getting more comfusing than I expected.
the cyclist
the cyclist 2016 年 11 月 19 日
The best form of thanks is upvoting and/or accepting helpful answers, which rewards the contributors, and guides future users.

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

カテゴリ

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