How can I find the maximum element of each column of a cell array

I have a cell array like this:
if true
ca={'x' 1 1 9 3;'y' 5 1 1 1; 'z' 5 7 5 9};
end
I have to find the max number of each column then divide all element of that column to maximum I wrote this code but it had errors:
if true
for j=2:3
max_column=max(ca(:,j));
for i=1:5
ca(i,j)= ca(i,j)/max_column;
end
end
disp(ca)
end
Please help me to edit this code. thanks in advance

 채택된 답변

Gopalkrishna Bhat
Gopalkrishna Bhat 2015년 5월 5일

0 개 추천

Hi Afsane,
The first column of char elements have to be removed & then the cell needs to converted to a matrix. Then you can run the code.
ba={'x' 1 1 9 3;'y' 5 1 1 1; 'z' 5 7 5 9};
temp = [ba(:,2),ba(:,3),ba(:,4),ba(:,5)];
ca = cell2mat(temp)
for j=1:4
max_column=max(ca(:,j));
for i=1:3
ca(i,j)= ca(i,j)/max_column;
end
end disp(ca)

댓글 수: 7

Please use proper formatting for code. People answering question are expected to know how to use the forum tools. You can either select the code part of your post, then click on the {} Code button, or just put two spaces before each line.
Secondly, learn to use matrix operations instead of loops. Your answer can be rewritten as:
ba={'x' 1 1 9 3;'y' 5 1 1 1; 'z' 5 7 5 9};
temp = ba(:, 2:5); %much clearer than concatenation
ca = cell2mat(temp);
max_column = max(ca); %no need for loop. max by default work on columns
ca = bsxfun(@rdivide, ca, max_column; %division of matrix by row
Afsane's comment moved here:
Hi dear friends
thanks for your answers but at the end of my code I have to convert regular array (ca) into cell array. How can I do that?
Use num2cell to convert the matrix back to a cell array
Thank you so much!!!
you mean like this?
for i=1:4
k=1;
for j=2:3
ba(i,j)=num2cell(ca(i,j));
k=k+1;
end
end
No, I mean:
ca(:, 2:end) = num2cell(ba);
for loops are often unnecessary in matlab. You can operate on the whole matrix / cell array at once.
Thanks a lot!!!

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

추가 답변 (1개)

Jos (10584)
Jos (10584) 2015년 5월 5일

1 개 추천

Life would be much easier if you didn't have your data arranges like this in the first place. How did you get this cell array? I strongly suggest you reconsider your approach.

댓글 수: 1

Stephen23
Stephen23 2015년 5월 6일
편집: Stephen23 2015년 5월 6일
Yes!
Strangely it seems to be the people with the most awkward and bizarre nested data arrangements that insist that "this is the only way" to arrange it, and that "it has to be this way..."... usually followed up with some painful loops and a whole brace [sic] of braces, parentheses and brackets...
Sigh

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

카테고리

도움말 센터File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

태그

질문:

2015년 5월 5일

편집:

2015년 5월 6일

Community Treasure Hunt

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

Start Hunting!

Translated by