How to simplify this for-loop into a one line of code?

조회 수: 10 (최근 30일)
Leon
Leon 2025년 3월 12일
댓글: dpb 2025년 3월 12일
Attached is a file storing a cell array A, a logical array for the columns: tf, and a logical array for A: map2.
My goal is to replace the below for-loops with a one line of code:
[m n] = size(A);
for j=1:n
for i=1:m
if ~tf(j) & map2(i,j)
A{i, j} = str2double(A{i,j});
end
end
end
Why doen't the below work?
A(~tf & map2) = str2double(A(~tf & map2));

채택된 답변

dpb
dpb 2025년 3월 12일
이동: dpb 2025년 3월 12일
load test10
whos
Name Size Bytes Class Attributes A 8x6 6076 cell ans 1x34 68 char map2 8x6 48 logical tf 1x6 6 logical
A
A = 8x6 cell array
{'ID12' } {[ 2]} {[-25.0100]} {[ 27.7690]} {[35.5800]} {'33RC1991'} {'ID12' } {[ 2]} {[-25.0020]} {[ 25.9660]} {[35.3670]} {0x0 char } {'ID12' } {0x0 char} {[-24.9930]} {[ 25.0250]} {[35.8480]} {'200105' } {0x0 char} {0x0 char} {[-25.0010]} {[<missing>]} {0x0 char } {'456' } {'2' } {'2' } {[-25.0020]} {[ 25.3260]} {[36.0880]} {'3689' } {'2' } {'2' } {[ -25]} {[ 26.1690]} {[35.9120]} {'3256778' } {'2' } {'2' } {[ -25]} {[<missing>]} {[36.2220]} {'33RC1991'} {'ID12' } {[ 2]} {[ -25]} {[<missing>]} {[36.3660]} {'33RC1991'}
~tf & map2
ans = 8x6 logical array
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0
A(~tf & map2)
ans = 3x1 cell array
{'2'} {'2'} {'2'}
try
A(~tf & map2)=str2double(A(~tf & map2))
catch ME
ME.message
A(~tf & map2)=num2cell(str2double(A(~tf & map2)))
end
ans = 'Conversion to cell from double is not possible.'
A = 8x6 cell array
{'ID12' } {[ 2]} {[-25.0100]} {[ 27.7690]} {[35.5800]} {'33RC1991'} {'ID12' } {[ 2]} {[-25.0020]} {[ 25.9660]} {[35.3670]} {0x0 char } {'ID12' } {0x0 char} {[-24.9930]} {[ 25.0250]} {[35.8480]} {'200105' } {0x0 char} {0x0 char} {[-25.0010]} {[<missing>]} {0x0 char } {'456' } {'2' } {[ 2]} {[-25.0020]} {[ 25.3260]} {[36.0880]} {'3689' } {'2' } {[ 2]} {[ -25]} {[ 26.1690]} {[35.9120]} {'3256778' } {'2' } {[ 2]} {[ -25]} {[<missing>]} {[36.2220]} {'33RC1991'} {'ID12' } {[ 2]} {[ -25]} {[<missing>]} {[36.3660]} {'33RC1991'}
You are trying to stuff a double array into a cell array -- "you can't do that!" :)
Convert the numeric array to equivalent in a cell array with num2cell.
My question is still what is wrong with the input file that caused this to happen and why not fix that instead?
  댓글 수: 2
Leon
Leon 2025년 3월 12일
It works. Thank you so much!
dpb
dpb 2025년 3월 12일
Can you not attach the file that creates the issue for somebody to poke at and see why it fails? If it is actually a flaw in readcell it could be a good tool for Mathworks; if there's something actually in the file, perhaps the generating process could be fixed instead.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

제품


릴리스

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by