Assigning columns of matrix to strings.

조회 수: 3 (최근 30일)
Karanvir singh Sohal
Karanvir singh Sohal 2021년 4월 6일
댓글: Karanvir singh Sohal 2021년 4월 6일
Hello everyone
I have following matrix which have nums and I have stored strings in another.
Name={'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' };
Data=[ 1 2 3 4 5 6 7 8 9 10 11
12 13 14 15 16 17 18 19 20 21 22
23 24 25 26 27 28 29 30 31 32 33];
Number of rows and columns can vary but number of strings will remain same as thr number of columns in Data matrix
I want to assign column matrix to corresponding strings
like:
a = [1; 12; 23]
b = [2; 13; 24]
..... and so on
  댓글 수: 3
Karanvir singh Sohal
Karanvir singh Sohal 2021년 4월 6일
Thanks @DGM. Its always good to learn new things.
I'm going through your suggested link.
Karanvir singh Sohal
Karanvir singh Sohal 2021년 4월 6일
My variables doesn't named as 'a' 'b'.... in my orignal code.
This is just an example.

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

채택된 답변

Stephen23
Stephen23 2021년 4월 6일
Naming variables dynamically is one way that beginners force themselves into writing slow, complex, buggy code:
Instead of doing that, you can write simple and efficient code by creating a structure:
Name={'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' };
Data=[ 1 2 3 4 5 6 7 8 9 10 11
12 13 14 15 16 17 18 19 20 21 22
23 24 25 26 27 28 29 30 31 32 33];
S = cell2struct(num2cell(Data,1),Name,2)
S = struct with fields:
a: [3×1 double] b: [3×1 double] c: [3×1 double] d: [3×1 double] e: [3×1 double] f: [3×1 double] g: [3×1 double] h: [3×1 double] i: [3×1 double] j: [3×1 double] k: [3×1 double]
S.a
ans = 3×1
1 12 23
S.b
ans = 3×1
2 13 24
  댓글 수: 4
Karanvir singh Sohal
Karanvir singh Sohal 2021년 4월 6일
I'll try to find possible solution to my problem and use "cell2struct".
Karanvir singh Sohal
Karanvir singh Sohal 2021년 4월 6일
@Stephen Cobeldick saved myself from code refactoring :)
figured out the error and possible solution for that.
Thanks once again.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Cell Arrays에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by