Replace an element in a cell array when a certain value only occurs once?

4 ビュー (過去 30 日間)
Jones
Jones 2017 年 9 月 11 日
コメント済み: Stephen23 2017 年 9 月 11 日
I have a cell array (x) with varying numbers of elements in each cell. In the instance where there is only one value in a cell (e.g. column 7), I would like to replace with a -1. I have tried a few approaches including these:
for sum = sum(x {i}(:,1) > 0);
if sum(1,1) == 1
x {i}(:,1) = 0;
end
end
and
oout=sum(cellfun(@double,x(:,1:19)))
I would appreciate any help here. Thanks

採用された回答

Stephen23
Stephen23 2017 年 9 月 11 日
Simpler:
>> a = rand(20,1);
>> c = {a,a,a,a,1,a,a,a,1,a,a,a};
>> c(cellfun(@isscalar,c)) = {-1}
  3 件のコメント
Jones
Jones 2017 年 9 月 11 日
I wasn't aware of the isscalar function, thanks!
Stephen23
Stephen23 2017 年 9 月 11 日
"I wasn't aware of the isscalar function, thanks!"
MATLAB has great documentation. Practice using it. In particular:
  1. the "See also" links at the bottom of each page for related functions and articles.
  2. the contents on the LHS, which are all links to topics and toolboxes.
  3. your favorite internet search engine can search the documentation too!
Practice using the documentation. It is the best and only source for knowing how to use MATLAB.

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

その他の回答 (1 件)

KL
KL 2017 年 9 月 11 日
a = rand(20,1);
x = {a,a,a,a,1,a,a,a,1,a,a,a};
sizes_x = cellfun(@(e) (size(e,1)*size(e,2))==1,x,'UniformOutput',false)
x(cell2mat(sizes_x)) = {-1};

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by