Newbie question about table indexing,loops and logical arguments (should be easy)
1 回表示 (過去 30 日間)
古いコメントを表示
Hello all,
Lets say I have a table with two variables. X contains either characters or various empty cells(,) like so: X = [A , , B , , , C ...] and Y contains a logical argument indicating if there are characters in X, like so: Y = [1 0 0 1 0 0 0 1 ...]. Now, I want to fill the empty cells in X for a new variable (Z) so the empty cells always contain the character in the cell above like so: Z = [A A A B B B B, C ...].
So far my code looks like this:
if table.Y == 1
table.Z = table.X (so far so good)
else table.Z = ? (and Im stuck...
I need to tell Matlab "go one up above in X and assign that value in Z" something like:
table.Z = table.X(i-1)...
Any ideas?
Thanks all for your patience!
0 件のコメント
回答 (2 件)
Jos (10584)
2016 年 6 月 3 日
I am not sure how you store your data. Here is an example with a cell array
X = {'A','','','B','B','','C','C',''}
Y = [1 , 0, 0, 1 , 1 ,0 , 1 , 1 , 0] % you can do without this one
Z = cell(size(A))
lastidx = 1 ;
Z{1} = A{1}
for k=2:N
if Y(k)==0, % you could use isempty(A{k}) here
Z{k} = A{lastidx}
else
Z{k} = A{k}
lastidx = k
end
end
0 件のコメント
Stephen23
2016 年 6 月 3 日
編集済み: Stephen23
2016 年 6 月 3 日
There is no need to waste time with an ugly loop:
>> X = {'A','','','B','B','','C','C',''};
>> idx = ~cellfun('isempty',X);
>> tmp = X(idx);
>> X = tmp(cumsum(idx))
X =
'A' 'A' 'A' 'B' 'B' 'B' 'C' 'C' 'C'
Note that this code assumes that the first cell is not empty (otherwise it throws an error).
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!