indexing with global variables in function statements

조회 수: 2 (최근 30일)
Muazma Ali
Muazma Ali 2017년 12월 15일
댓글: Walter Roberson 2017년 12월 15일
Hi! can I not include a global variable in an output in a function like this:
function sigma_v_eff_sona(zone_number,1)=effective_stresses()
when I declare zone_number as global variable in effective_stresses. Do I have to skip the index zone_number in the output statement since I have declared zone_number as a global variable in the mentioned function?
  댓글 수: 2
KL
KL 2017년 12월 15일
The question is why do you need it as a global variable?
Muazma Ali
Muazma Ali 2017년 12월 15일
because i am using it in many functions

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

답변 (2개)

Walter Roberson
Walter Roberson 2017년 12월 15일
The left hand side of the = of a function statement must be plain variables names, not indexed, not structure references, not cell array references.
In MATLAB, if you want to have a function that changes only some portions of the output variable, then the variable must be input as well, such as
function sigma_v_eff_sona = effective_stresses(sigma_v_eff_sona)
global zone_number
sigma_v_eff_sona(zone_number,1) = ...
  댓글 수: 4
Muazma Ali
Muazma Ali 2017년 12월 15일
편집: Walter Roberson 2017년 12월 15일
ok, this is how it looks like in my script:
zone_number=0;
while .....
zone_number=zone_number+1;
max_pressure=maks_trykk_perm() % this function calls sigma_v_effective_stress=effective_stresses()
in this case where should I preallocate the array called sigma_v_effective_stress?
in my programme i have several such arrays somehow within the while loop but not directly. They are supposed to have max 40 values each.
Walter Roberson
Walter Roberson 2017년 12월 15일
I think you should rewrite as a for loop. Perhaps something similar to
max_zones = 40;
max_pressure = zeros(1, max_zones);
old_max_pressure = inf;
for zone_number = 1 : max_zones
this_pressure = maks_trykk_perm();
if abs( this_pressure - old_max_pressure) < 0.001
break; %close enough to end the loop early?
end
max_pressure(zone_number) = this_pressure;
...
end

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


the cyclist
the cyclist 2017년 12월 15일
편집: the cyclist 2017년 12월 15일
Are you getting the error "Unexpected MATLAB expression"? The global variable is irrelevant. The following is not a valid way to output from a MATLAB function.
function x(1) = answerTest()
x = [3 2];
end
You need to do the indexing in the function, then output a "whole" variable.

카테고리

Help CenterFile 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