How can I use different array names in a loop?

Hello,
Suppose I have 4 arrays as,
a_1_b;
a_2_b;
a_3_b;
a_4_b
all the arrays are of same size. I want to add something in the first column of each of the arrays, but I am not sure how to do this. as example:
for i=1:4
a_i_b(:,1)=a_i_b(:,1)+7
end
this is not the right way. Can anyone please show me the correct way?
Thanks!

 채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2013년 6월 11일
편집: Azzi Abdelmalek 2013년 6월 11일

0 개 추천

for i=1:4
evalin('base',sprintf('a_%d_b(:,1)=a_%d_b(:,1)+7',i,i))
end
%or
for i=1:4
data=7
evalin('base',[sprintf('a_%d_b(:,1)=a_%d_b(:,1)+',i,i) num2str(data)])
end

댓글 수: 1

Jan
Jan 2013년 6월 11일
Avoid EVAL and EVALIN in general. Both increase the komplexity and reduce the efficiency, and there are always cleaner and faster methods.

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

추가 답변 (3개)

Jan
Jan 2013년 6월 11일

2 개 추천

See http://www.mathworks.com/matlabcentral/answers/57445-faq-how-can-i-create-variables-a1-a2-a10-in-a-loop: It is strongly recommended not to hide indices in the names of variables, but touse indices instead.
ab = cell(1, 4);
ab{1} = rand(2,3);
ab{2} = rand(2,3);
ab{3} = rand(2,3);
ab{4} = rand(2,3);
for k = 1:4
ab{k}(:,1) = ab{k}(:,1) + 7
end

댓글 수: 1

Nazmul
Nazmul 2013년 6월 11일
thanks a lot, Simon... That FAQ was also helpful.

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

Andrei Bobrov
Andrei Bobrov 2013년 6월 11일

0 개 추천

n = sprintf('a_%d_b,',1:4);
a_b = eval(['{',n(1:end-1),'}']);
a_b = cellfun(@(x)[x(:,1) + 7,x(:,2:end)],a_b,'un',0);
Nazmul
Nazmul 2013년 6월 11일

0 개 추천

Thanks a lot. All the 3 solutions were helpful.

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by